Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle stack array allocation failure in C?

If I have to write some code like below:

int a[10000000];

I know that the code might fail sometimes due to stack overflows. The question is how to handle such errors at runtime, and avoid the segfault?

like image 509
Moeb Avatar asked Apr 27 '26 20:04

Moeb


1 Answers

In general, stack overflow exceptions are very difficult to handle in a graceful way. This is because the stack is already overflowed, and in order for more code (even exception handling code) to run there needs to be stack space available.

In general, programmers design programs so that they cannot overflow the stack. This involves:

  • keeping the size of automatic variables allocated on the stack to a minimum (and using other types of allocation if large data structures are needed)
  • avoiding unnecessary recursion, and if recursion is used, ensuring that there are reasonable constraints on the maximum depth

If you need space for ten million integers inside a function, don't allocate it on the stack - allocate it using malloc() or new (depending on whether you are actually using C or C++). Of course it is also your responsibility to free() or delete it when you are done with it.

If you are really using C++[1], then you should probably be using std::vector instead:

std::vector a(10000000);

The underlying standard library implementation will allocate the space on the free store, and will automatically deallocate it for you when your function returns.

[1] I wish people wouldn't tag questions with both c and c++ just because they are spelled similarly.

like image 52
Greg Hewgill Avatar answered Apr 30 '26 11:04

Greg Hewgill