local array causes segfault

Recently while working on a C program I was intermittently getting a segfault. The code appeared correct yet it would inexplicably crash, seemingly at random. I compiled the program with the ‘-g’ flag to enable debugging symbols, and discovered I was dealing with the dreaded stack overflow.

Exception: STATUS_STACK_OVERFLOW at rip=00100414BC6

The line of code in question was the declaration of a large local array. Something like:


The fix was really simple. I just replaced that line of code with this one:

int* foo = malloc(REALLY_BIG_NUMBER * sizeof(int));
// later on...
free(foo); // <--- very important!

That's it. The difference is the area of memory that the data is allocated in. In the former example (the local array), the compiler used stack memory. The stack is an area of memory used for temporary variables created by each function. By allocating a large array, I tried to fit more into the stack than it could accommodate, hence the 'stack overflow'. In the latter example, a different area of memory is used called the heap. The heap is not as tightly managed and is somewhat larger.

This entry was posted in Software Development. Bookmark the permalink.