Hot interview questions: 01 – Stack Overflow

Categories: Others


stack overflow

There are some topic that a software engineer has to master, like what is a stack overflow, stack unwinding, how does memory works, difference between throughput and latency and so on. So as of today I’ll write one post for every “hot interview questions”, starting from what a stack overflow is!.

Automatic memory

First off … the stack: in the programmer’s view (I’m assuming C++ in this case but that’s not so different on other languages) the memory is a “pile” split up in: static, automatic and dynamic (see “the C++ programming language”, Stroustrup). The stack section is the automatic section in which are stored all the local variables, structures, object and the method calls are taken place. In the below code the variable x is stored in the automatic memory section (commonly called stack).

 int foo () {
   int x;

the address of the foo method is stored in the stack too … the stack memory is not infinite so the stack overflow exception is around the corner.

Stack Overflow

In two circumstances a stack overflow can come out: 1) object allocated too big or 2) infinite (or too depth) recursion. But the problem is just one, the stack pointer has exceeded the stack bound of the process.

First Case (object too big)

int foo () {
   // where MY_OBJ is big itself.
   MY_OBJ myLocalObj[1000000000000000];

in this case the stack will not contain such a big object and a “stack overflow” exception will be raised to the process. Solution in this case is to allocate MY_OBJ object on the Heap section (or dynamic memory). And, btw, recommendation is to allocate objects on the stack till few k.

Second Case (infinite recursion)

int foo () {
   foo ();

in this case the foo() method will be called till when the exception will be called. The reason is that even though is the same method a new “instance” of the foo() method has to be called. In that case the end recursion condition is missing.


    Leave a Reply

    Your email address will not be published.

    This site uses Akismet to reduce spam. Learn how your comment data is processed.