How to avoid stack overflow error in C?
Question: what are ways that the compiler can cause the stack to overflow?
I was under the impression it only did when you access an array out of its bounds? Your compiler can also cause your program to overwrite important variables (eg those used to create new arrays) that are local to a function. You have no reasonable way to prevent the compiler from doing this, as they can do all kinds of things on your behalf. It would be far more productive to learn how to write C with proper control statements and use of the stack, rather than learning how to protect against compiler exploits.
What can cause stack overflow in C?
Can anyone help me in figuring out .
I am trying to get answers from experts but I dont have any clue where to start. I have a recursive function: static void recursion(void). When I enter the value for I as 99999999, I get stack overflow. How can that be possible? Also, how does the stack work and what is exactly happening? When recursion is used, the return address is placed on the stack. When the function returns, it will fetch the return address, jump back there, and start executing the function. The problem is that your stack gets so large (or maybe overflows), that the program reaches an invalid address and starts trying to find the original return address (the program counter).
You may want to take a look at wikipedia or a good book about compilers. Your recursive function takes an integer, i, and prints a message and calls itself. At some point, you're doing a recursion with more than 32,767,000 iterations.
A stack overflow happens when the operating system runs out of memory.
How to stop stack overflow in C?
I have some C code which contains a lot of recursion.
I am currently trying to understand how to fix the issue of stack overflow by looking at other solutions. However, I am having a hard time finding an actual solution. I have already tried the following:
Put a large enough stack size. Put all function arguments at the top of the stack. Put all local variables at the top of the stack. These options have not helped. Can anyone explain how to fix this? The most common solution is to have the stack grow automatically. This is done by using an array of fixed-size blocks on the stack (as opposed to an array of dynamically allocated blocks). There are two ways to do this:
Use a circular buffer (eg on Linux, see stksetbuf()). Use a fixed-size stack block (eg on Linux, see asm/stack.h).
The latter approach is generally preferred as it's easier to keep track of where the stack ends and the heap begins.
Related Answers
Why is Stack Overflow so popular?
The first few days of my employment at Stack Overflow are a bit hazy....
What is stack overflow with example?
A Stack overflow is when a process will only ever be able to add or re...
What is stack overflow error message in C?
A stack overflow occurs when a program runs the virtual functi...