Skip to main content

Stack Overflow Micro-HOWTO

You may have heard about stack overflow (no, not the web site), but you may nave never had a chance to experience what that really is.

In Linux you can control the stack size with "ulimit -s". By default it is 8 MB on Ubuntu machine:

$ ulimit -s
8192

The program below causes a stack overflow. Please note that the application does nothing, however it manages to fill its stack space completely.

int main(int argc, char** argv) {
    char stack[8192 * 1024];
    return 0;
}
$ gcc -o stack stack.c
$ ./stack
Segmentation fault (core dumped)

Even though 8Mb is available to the program, there are various other things that need to be put on the stack, such as the arguments and return values. When a recursive function breaks and calls itself indefinitely it eventually uses up all the stack space and crashes in exactly the same way.

Read more about this in the C++ Tutorial.