Call Stack and Stack Overflows

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:

_returnZero:
        xorl    %eax, %eax
        ret

Author: 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.

 
Notice an error in any content or would like to get something removed? Please inform Victor here.

Leave a Reply

Your email address will not be published. Required fields are marked *