Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't you free variables on the stack?

The languages in question are C/C++.

My prof said to free memory on the heap when your done using it, because otherwise you can end up with memory that can't be accessed. The problem with this is you might end up with all your memory used up and you are unable to access any of it.

Why doesn't the same concept apply to the stack? I understand that you can always access the memory you used on the stack, but if you keep creating new variables, you will eventually run out of space right? So why can't you free variables on the stack to make room for new variables like you can on the heap?

I get that the compiler frees variables on the stack, but thats at the end of the scope of the variable right. Doesn't it also free a variable on the heap at the end of its scope? If not, why not?

like image 493
dfg Avatar asked Nov 02 '13 23:11

dfg


1 Answers

Dynamically allocated objects ("heap objects" in colloquial language) are never variables. Thus, they can never go out of scope. They don't live inside any scope. The only way you can handle them is via a pointer that you get at the time of allocation.

(The pointer is usually assigned to a variable, but that doesn't help.)

To repeat: Variables have scope; objects don't. But many objects are variables.

And to answer the question: You can only free objects, not variables.

like image 92
Kerrek SB Avatar answered Oct 29 '22 13:10

Kerrek SB