Question about clearing/free up memory

I'm still not too familiar with the concept of properly clearing memory space

when you create a variable in a function and call it multiple times, will it store multiple instances of the variable within your memory? or will the program automatically clear the variable out of the memory after the function is finished?

void doSomething()
int a = 10;

Also, will an object's destructor be automatically called once you exit the program?

I just don't want random data from the program to still be stored within the memory once I close the program.


(I'm used to programming in C# which had garbage collection, but I know it is a feature that C++ lacks)
Last edited on
Multiple instances, yes, but not simultaneously. In your example, a will be placed on the stack every time the function is called. But once the function exits, everything that was pushed onto the stack inside the function gets destroyed. Ideally I'd give a link or provide a visual, but I'm on mobile.

Heap allocation is what you really need to worry about (new and delete). That memory won't be destroyed unless you destroy it. Regardless of if you destroyed it however, any memory on the heap is gotten rid of by windows once the program exits.

Destructors are automatically called when an object on the stack goes out of scope. For memory on the heap, they are called after using delete.
Last edited on
Alright thanks!
Topic archived. No new replies allowed.