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?
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With