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

Viewed 252

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)

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.

Related