Eli5-What does a “stack overflow” mean?

1.26K views

Eli5-What does a “stack overflow” mean?

In: 847

41 Answers

Anonymous 0 Comments

Just to add to the other answer:

All memory in a computer has to be declared and reserved in some way by a program, so your operating system knows that *this* block of memory currently belongs to your program and is not available to some other process running in the background. Trying to access memory that hasn’t been reserved results in the OS terminating the program.

In computers, memory can be reserved either on the stack or the heap. The heap is for more permanent memory reservation: you have to explicitly tell the computer how much memory you want to reserve, and then you have to tell it when you don’t want it any more and it can be freed for another program to use (side note: a “memory leak” occurs when a program reserves some memory, finishes using it, but due to a programming oversight never tells the OS to free it again). Once reserved, heap memory remains reserved until the program asks for it to be freed again.

Stack memory is slightly different: it is reserved by the OS automatically when a function (a particular section of your code) starts executing, and is automatically freed when the function finishes. It acts as a “scratch pad” for that function so you can do convenient things like this:

`int MyAddFunction(int a, int b)
{
int result = a + b;
return result;
}`

In this case: where is “result” stored? You never asked for that memory to be reserved. The answer is the stack: the OS will automatically reserve memory for “result”. Once the function finishes (at the return point), then the memory block for “result” is automatically freed up.

A stack overflow occurs when you use too much memory within a function. Stack size is pretty small (around 1mb I think?), so you could create a stack overflow either by trying to automatically reserve some huge data structure, or by running a loop that requests millions of little ones. In that situation, you would want to reserve some memory on the heap, and then remember to free it at the end of your function before it finishes.

Just to note: a lot of high level programming languages nowadays like Java, C# etc. manage memory for you so you don’t have to explicitly reserve it and free it on the heap.

You are viewing 1 out of 41 answers, click here to view all answers.