Why doesn't the following code produce a segmentation fault? [duplicate]

你。 提交于 2020-01-06 03:02:26

问题


#include <iostream>
using namespace std;

int a[4];
int main(){
    int b=7;
    cout<<a[b]<<endl;
    return 0;
}

I was trying to access the memory that was not allocated. So I expect the output to be a segmentation fault,instead the output is some garbage value.

Later I increased 'b' to 1000, now the output is 'Segmentation fault'. Is there a specific reason for this kind of behaviour?

I'm using gcc-4.3.2 compiler.


回答1:


A segmentation fault may be thrown if you are attempting to access a nonexistent memory address (outside process's address space).

a[7] might not be outside its accessible space in this case but a[1000] most certainly is. But even the former will blow up, when you least expect it ;)




回答2:


Segmentation faults only occur if you access memory that the operating system has not allowed you to access.

However, you can access memory that, while it isn't what you expect, has been granted to you, for example memory addresses that point earlier or later into the stack. But it's not something that you can rely on being consistent, as how locally stored variables are placed on the stack is decided by the compiler according to arcane optimizations that will vary - from debug to release, as your code changes, etc.

But if you ever see something like, 'why does accessing this variable give me garbage, but always the same garbage?' you're probably unintentionally peeking at parts of the stack you ought not to.




回答3:


It's undefined behaviour so anything can happen, you just can't tell. Check this out (for C++) to know the difference between undefined behaviour, unspecified behaviour, and implementation defined behaviour.

C - **ISO C9899** in Annex J clearly talks about this.

EDIT
C++ - N3485 ISO/IEC in section 1.9.2 ,1.9.3 , 1.9.4 talks about the above behaviors.




回答4:


Out of bounds access is undefined behavior. It can access arbitrary memory in your process space. If the accessed memory is not allocated or not in process address space (may be in kernel) then you program will crash with segmentation fault. In such cases faults will help you identify problem and if lucky will get a crash else it may get unnoticed and will get some bug later in program corrupting memory which is then difficult to track. The probabilty of a[1000] to be un allocated is more and hence the crash. Memory is allocated in pages.




回答5:


Undefined behaviour isn't required to cause segfaults. Consider int i = INT_MAX + 1; for another example of undefined behaviour that doesn't commonly cause a segfault.



来源:https://stackoverflow.com/questions/15871423/why-doesnt-the-following-code-produce-a-segmentation-fault

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!