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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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()ornew(depending on whether you are actually using C or C++). Of course it is also your responsibility tofree()ordeleteit when you are done with it.If you are really using C++[1], then you should probably be using
std::vectorinstead: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.