Sunday, January 13, 2013

local variable in memory

The theory is, whenever you create variable without *, it is stored in the stack. but it you create variable with *, it is stored in the heap.

I will give you example,
void foo()
{
   int x = 10;
}
After the program leave function, x will be deleted from the memory.

void foo()
{
   int *a;
}
After the program leave function, a will also be deleted from the memory.

Different case with like this,
void foo()
{
   int *b = new int(10); // here, you create an object of integer
   delete b; // before leaving the function, you have to delete your object. Otherwise you will get memory leak.
}

No comments:

Post a Comment