Call Stack and Stack Overflows

By October 13, 2017 July 21st, 2019 No Comments

In computer science, a call stack is a stack data structure that stores information about the active subroutines of a computer program. This kind of stack is also known as an execution stack, program stack, control stack, run-time stack, or machine stack, and is often shortened to just “the stack”.

Read more at Wikipedia

Stack Overflows

Whenever you call a function, including recursively, the return address and often the arguments are pushed onto the call stack. The stack is finite, so if the recursion is too deep you’ll eventually run out of stack space.

The size of the stack is configurable. On Unix, the command is ulimit -s. Remember, you wouldn’t get the entire stack space for just one program. Some of it is also used for general housekeeping.

Given that the function is tail-recursive, some compilers might be able to optimize the recursive call away by turning it into a jump. Some compilers might take your example even further: when asked for maximum optimizations, gcc 4.7.2 transforms the entire function into:

int returnZero(int anyNumber){
  return 0;

This requires exactly two assembly instructions:

        xorl    %eax, %eax

Recursive functions should therefore be used with extreme caution. Your programs may fail if the number of function calls exceed your call stack.

Victor Fernandes

Victor Fernandes

A friend I really respect once told me, unless you are able to dumb down a concept for someone who has no prior information about it, you can't be sure you know it yourself. I try to create blog posts that are extremely easy to understand most suitable for those in a hurry. The topics I write about include web development, digital marketing and software in general.

Leave a Reply

Contact Me

If you prefer email, you may also email me at [email protected]