To get a trial key
fill out the form below
Team License (a basic version)
Enterprise License (an extended version)
* By clicking this button you agree to our Privacy Policy statement

Request our prices
New License
License Renewal
--Select currency--
* By clicking this button you agree to our Privacy Policy statement

Free PVS-Studio license for Microsoft MVP specialists
* By clicking this button you agree to our Privacy Policy statement

To get the licence for your open-source project, please fill out this form
* By clicking this button you agree to our Privacy Policy statement

I am interested to try it on the platforms:
* By clicking this button you agree to our Privacy Policy statement

Message submitted.

Your message has been sent. We will email you at

If you haven't received our response, please do the following:
check your Spam/Junk folder and click the "Not Spam" button for our message.
This way, you won't miss messages from our team in the future.

Stack Overflow

Stack Overflow

Jul 08 2013


A stack overflow is a run-time software bug when a program attempts to use more space than is available on the run-time stack, which typically results in a program crash.

Run-time Stack

A run-time stack is a special area of computer memory that works on the LIFO principle (Last in, first out: the last element added to a structure must be the first one to be removed). The word "stack" refers to the manner in which several plates are stacked: you form a stack by putting the plates on top of each other (this way of adding an object into the stack is called "push") and then remove them starting with the top plate (this way of removing an object from the stack is known as "pop"). Run-time stack is also known as call stack, execution stack and machine stack (these terms are used in order not to mix it up with the "stack" as an abstract data structure).

The purpose of a stack is to allow the programmer to conveniently arrange calls of subroutines. A stack can be used to store arguments to be passed to a function being called and its local variables. If another function is called by the first one, it can pop the arguments from the stack and use them, as well as store its own variables in a memory area allocated for this function. As it returns control, it also clears and frees the stack memory. High-level language programmers usually don't bother about such things, for the task of generating the necessary routine code is performed solely by the compiler.

Consequences of the Bug

We have finally got close to the subject of our discussion. As an abstraction, a stack is an infinite storage you can endlessly add new items into. Unfortunately, everything is finite in the real world - stack memory is no exception. What will happen when it runs out as new arguments are being pushed into it or when a function allocates memory to store its variables?

An error known as a stack overflow will occur. Since a stack is used to arrange calls of user subroutines (and most programs written in contemporary programming languages - including object-oriented ones - actively employ functions one way or another), the program won't be able to call any function after the error occurs. When that happens, the operating system takes control back, clears the stack and terminates the program. Here lies the difference between the buffer overflow and the stack overflow. The former occurs when the program attempts to access a memory area outside the buffer's boundary and remains unnoticed if there is no protection against that; the program goes on to run correctly if lucky enough. It's only when there is memory protection that a segmentation fault occurs. But when a stack overflow occurs, the program inevitably crashes.

To be most precise, this scenario is only true for native languages. The virtual machine in managed languages has its own stack for managed programs, which is easier to monitor, so that you can even afford throwing an exception when a stack overflow occurs. But C and C++ cannot afford such a "luxury".

Reasons for the Bug

What are the reasons for this unpleasant error? Keeping in mind the above described mechanism, we can name one: too many embedded function calls. This scenario is especially probable when using recursion: it is actually this error that infinite recursion terminates with (when there is no lazy evaluation mechanism), unlike an infinite loop which may be useful at times. However, when there is a very small area of memory allocated on the stack (which is, for instance, typical of microcontrollers), just a short sequence of calls will do the job.

Another reason is local variables requiring too much stack memory. It's a bad idea to create a local array of a million of items or a million local variables (just in case). Just one call of such a "greedy" function may easily trigger a stack overflow. If you want to get large data amounts, you'd better use dynamic memory to be able to process an error in case it runs out.

Dynamic memory, however, is quite slow to allocate and free (because it is managed by the operating system). Besides, you have to manually allocate and release it when provided with a direct access. Conversely, stack memory is allocated very quickly (in fact you just need to change the value of one register); moreover, objects allocated on the stack are automatically destroyed when the function returns control and clears the stack. You naturally can't help the urge to exploit it. Therefore, the third reason for the bug is manual allocation of stack memory by the programmer. The C library provides the special function alloca for this purpose. An interesting thing is that while the malloc function (intended to allocate dynamic memory) has a "sibling" that frees it (the free function), the alloca function has none: memory is freed automatically once the function returns control. This thing is likely to complicate the issue, for you can't free memory before leaving the function. Though the man page for the alloca function clearly reads that it "is machine- and compiler-dependent; on many systems it cannot be used properly and may cause errors; its use is discouraged", programmers still use it.


As an example, let's study a code fragment performing recursive file search (taken from MSDN):

void DirSearch(String* sDir)
         // Find the subfolders in the folder that is passed in.
         String* d[] = Directory::GetDirectories(sDir);
         int numDirs = d->get_Length();
         for (int i=0; i < numDirs; i++)
             // Find all the files in the subfolder.
             String* f[] = Directory::GetFiles(d[i],textBox1->Text);
             int numFiles = f->get_Length();

             for (int j=0; j < numFiles; j++)
     catch (System::Exception* e)

This function receives the list of items in the specified folder and then recursively calls itself over those items which are folders. If the file tree is deep enough, the result of this is quite obvious.

Here is an example to illustrate the second reason taken from the question "What might be the reason for a stack overflow exception?" asked at Stack Overflow (this is a question-and-answer website dealing with all programming-related topics, not only stack overflow, as one may conclude from its name):

#define W 1000
#define H 1000
#define MAX 100000 
int main()
    int image[W*H];
    float dtr[W*H];
    return 0;

As you can see, the main function asks for some stack memory to be allocated for an int-array and a float-array, one million items each, which gives just a bit less than 8 Mbytes in total. If we recall that Visual C++ by default reserves only 1 Mbyte for the stack, we can easily answer that question.

And, finally, here is an example taken from the GitHub-repository of the Flash-player Lightspark project:

DefineSoundTag::DefineSoundTag(/* ... */)
    // ...
    unsigned int soundDataLength = h.getLength()-7;
    unsigned char *tmp = (unsigned char *)alloca(soundDataLength);
    // ...

One may hope that h.getLength()-7 won't grow too big and no overflow will occur in the next line. But is the time saved on memory allocation worth a potential crash?


Stack overflow is a fatal error which is most often found in programs containing recursive functions. It can also be caused by pushing too many local variables into the stack or manual allocation of stack memory. Stick to the old good rules: when you have a choice, prefer iteration to recursion, and avoid manual interference in what the compiler does better.


Popular related articles
The Evil within the Comparison Functions

Date: May 19 2017

Author: Andrey Karpov

Perhaps, readers remember my article titled "Last line effect". It describes a pattern I've once noticed: in most cases programmers make an error in the last line of similar text blocks. Now I want t…
The Ultimate Question of Programming, Refactoring, and Everything

Date: Apr 14 2016

Author: Andrey Karpov

Yes, you've guessed correctly - the answer is "42". In this article you will find 42 recommendations about coding in C++ that can help a programmer avoid a lot of errors, save time and effort. The au…
How PVS-Studio Proved to Be More Attentive Than Three and a Half Programmers

Date: Oct 22 2018

Author: Andrey Karpov

Just like other static analyzers, PVS-Studio often produces false positives. What you are about to read is a short story where I'll tell you how PVS-Studio proved, just one more time, to be more atte…
The Last Line Effect

Date: May 31 2014

Author: Andrey Karpov

I have studied many errors caused by the use of the Copy-Paste method, and can assure you that programmers most often tend to make mistakes in the last fragment of a homogeneous code block. I have ne…
Characteristics of PVS-Studio Analyzer by the Example of EFL Core Libraries, 10-15% of False Positives

Date: Jul 31 2017

Author: Andrey Karpov

After I wrote quite a big article about the analysis of the Tizen OS code, I received a large number of questions concerning the percentage of false positives and the density of errors (how many erro…
Static analysis as part of the development process in Unreal Engine

Date: Jun 27 2017

Author: Andrey Karpov

Unreal Engine continues to develop as new code is added and previously written code is changed. What is the inevitable consequence of ongoing development in a project? The emergence of new bugs in th…
Appreciate Static Code Analysis!

Date: Oct 16 2017

Author: Andrey Karpov

I am really astonished by the capabilities of static code analysis even though I am one of the developers of PVS-Studio analyzer myself. The tool surprised me the other day as it turned out to be sma…
The way static analyzers fight against false positives, and why they do it

Date: Mar 20 2017

Author: Andrey Karpov

In my previous article I wrote that I don't like the approach of evaluating the efficiency of static analyzers with the help of synthetic tests. In that article, I give the example of a code fragment…
PVS-Studio for Java

Date: Jan 17 2019

Author: Andrey Karpov

In the seventh version of the PVS-Studio static analyzer, we added support of the Java language. It's time for a brief story of how we've started making support of the Java language, how far we've co…
PVS-Studio ROI

Date: Jan 30 2019

Author: Andrey Karpov

Occasionally, we're asked a question, what monetary value the company will receive from using PVS-Studio. We decided to draw up a response in the form of an article and provide tables, which will sho…

Comments (0)

Next comments
This website uses cookies and other technology to provide you a more personalized experience. By continuing the view of our web-pages you accept the terms of using these files. If you don't want your personal data to be processed, please, leave this site.
Learn More →