Can C / C ++ read seg-fault after end of array (UNIX)?

I know that you can read the last end of the array - now I wonder if you can seg-fault just perform this read operation.

int someints[100]; std::cerr << someints[100] << std::endl; //This is 1 past the end of the array. 

Can the second line actually cause seg-fault or just print jibberish? Also, if I change this memory, can it cause a seg-fault on this particular line , or will the error only happen later when something else tries to use this randomly changed memory?

+7
source share
3 answers

This behavior is undefined and completely depends on the virtual memory scheme that the operating system organized for this process. Typically, you can:

  • access some gibberish that belongs to your virtual address space but has no meaning or
  • tries to access the limited memory address, in which case the memory display hardware causes a page error, and the OS decides whether to tear off your process or allocate more memory.

If someints is an array on the stack and the last variable declared, you are likely to get some gibberish from the top of the stack or (very unlikely) cause a page error that can either allow the OS to resize the stack or kill your process using SIGSEGV .

Imagine that you declared a single int right after your array:

 int someints[100]; int on_top_of_stack = 42; std::cerr << someints[100] << std::endl; 

Then, most likely, the program should print 42 , if the compiler somehow does not order the order of declarations on the stack.

+9
source

Yes, it can segfault if the memory at this address is not accessible by the program. In your case, it is unlikely that the array is distributed on the stack and has a length of only 100 bytes, and the stack size is much larger (i.e. 8 MB per stream in Linux 2.4.X), so there will be uninitialized data. But in some cases, it may fall. In any case, this code is erroneous, and profilers such as Valgrind should be able to help you fix it.

+4
source

The second line can lead to something literally happening and still be correct in relation to the language specification. He could print gibberish, he could crash due to a segmentation error or something else, this could lead to power disappearing along the entire east coast, or it could cause canonical demons to fly out of your nose ...

This magic is undefined behavior .

+2
source

All Articles