I’m aware that you can read past the end of an array – I’m wondering now if you can seg-fault just by performing that reading operation though.
int someints[100];
std::cerr << someints[100] << std::endl; //This is 1 past the end of the array.
Can the second line actually cause a seg-fault or will it just print jibberish? Also, if I changed that memory, can that cause a seg-fault on that specific line, or would a fault only happen later when something else tried to use that accidentally changed memory?
This is undefined behaviour and entirely depends on the virtual memory layout the operating system has arranged for the process. Generally you can either:
If
someintsis an array on the stack and is the last variable declared, you will most likely get some gibberish off the top of the stack or (very unlikely) invoke a page fault that could either let the OS resize the stack or kill your process with aSIGSEGV.Imagine you declare a single
intright after your array:Then most likely the program should print
42, unless the compiler somehow rearranges the order of declarations on the stack.