Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: Can a too large stack lead to a segmentation fault?

I have recently debugged a very strange problem that caused a segmentation fault.

Basically, the problem went away after I have moved a couple of very large arrays that were declared as local variables to being global, which means as far as I know that I moved them from the stack to the heap space. Nothing else was changed. The segmentation fault itself appeared in very old and stable code that was also shared across other programs that did not experience any segmentation faults.

In total, these arrays were about 1.5 MB in size.

Is it possible that a too large stack can cause a segmentation fault by overwriting/messing up function pointers?

My feeling is that such a thing should be caught by the compiler, but I have absolutely no other way of explaining this behaviour.

The platform is Linux (Ubuntu 18.04)

like image 676
Roland Seuhs Avatar asked Mar 16 '20 13:03

Roland Seuhs


People also ask

Can out of memory cause segmentation fault?

Segmentation fault is an error caused by accessing invalid memory, e.g., accessing variable that has already been freed, writing to a read-only portion of memory, or accessing elements out of range of the array, etc.

What causes segmentation fault 11?

1) Segmentation Fault (also known as SIGSEGV and is usually signal 11) occur when the program tries to write/read outside the memory allocated for it or when writing memory which can only be read.In other words when the program tries to access the memory to which it doesn't have access to.


1 Answers

The stack size of a program is limited, so declaring too many large arrays as local variables can cause a stack overflow. What you did is a good way of handling the issue.

It's not something that compilers typically check for, as stack size is controlled at run time by the OS, for example ulimit -s or getrlimit/setrlimit on Linux systems. The man page for getrlimit states the following regarding stack size:

RLIMIT_STACK

The maximum size of the process stack, in bytes. Upon reaching this limit, a SIGSEGV signal is generated. To handle this signal, a process must employ an alternate signal stack (sigaltstack(2)).

So on Linux, the size of the stack is a run-time setting, and overrunning the stack explicitly causes a segmentation violation.

like image 195
dbush Avatar answered Oct 17 '22 11:10

dbush