Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a C/C++ program seg-fault from reading past the end of an array (UNIX)?

Tags:

c++

c

unix

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?

like image 793
John Humphreys Avatar asked Aug 31 '11 17:08

John Humphreys


1 Answers

This is undefined behaviour and entirely depends on the virtual memory layout the operating system has arranged for the process. Generally you can either:

  • access some gibberish that belongs to your virtual address space but has a meaningless value, or
  • attempt to access a restricted memory address in which case the memory mapping hardware invokes a page fault and the OS decides whether to spank your process or allocate more memory.

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.

like image 146
Blagovest Buyukliev Avatar answered Sep 20 '22 15:09

Blagovest Buyukliev