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 someints
is 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 a SIGSEGV
.
Imagine you declare 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
, unless the compiler somehow rearranges the order of declarations on the stack.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With