There are 3 kinds of variables. Depending on the kind you manage the memory differently.
Global Variables
These reside in a special section of your program. They appear when the program starts and disappear when the program ends. You cannot do anything to reclaim the memory occupied by global variables.
Some more complex constants may fall into that category as well. Your character string literal "I don't want this cleared, but completely gone"
is most likely going to reside there, no matter if you copy it to i_want_to_delete_this
variable or not.
Stack Variables
Local variables and function arguments. They appear within your code. The memory is allocated when you enter the scope of that variable, and are removed automatically when you leave the scope:
{ //beginning of the scope
int foo = 42; // sizeof(int) bytes allocated for foo
...
} //end of the scope. sizeof(int) bytes relaimed and may be used for other local variables
Note that when optimizations are on, local variables may be promoted to registers and consume no RAM memory at all.
Heap Variables
Heap is the only kind of memory you manage yourself. In plain C you allocate memory on the heap using malloc
and free it with free
, e.g.
int* foo = (int*)malloc(sizeof(int)); //allocate sizeof(int) bytes on the heap
...
free(foo); //reclaim the memory
Note that the foo
itself is a local variable, but it points to a portion of heap memory where you can store an integer.
Same thing in C++ would look as:
int* foo = new int; //allocate sizeof(int) bytes on the heap
...
delete foo; //reclaim the memory
Heap is usually used when the variable must exist much longer than the scope, usually depending on some more complex program logic.