Say I’m declaring primitives or arrays of primitives (on the stack right). How do I “free” or clean them up so they aren’t taking/leaking memory?
For example:
int blah;
blah=7;
doSomethingWithBlah...
free(blah) //[?]
probably not a bit deal normally; but what if you had say a huge char array or whatever?
also any ‘local’ variables (that is, inside a function) will be by default ‘auto’ and are cleaned up automatically right [in Java terms, they are GCed when going out of scope).
Just curious, thanks.
You don’t.
A stack is a data structure. It’s LIFO (Last In, First Out) which means that the last thing that was put on the stack is the first one to be removed from the stack. Here’s how you can think about this in programming:
main -> foo
The main function (entry point) calls some function foo. Certain variables are declared/defined in the main function. Others are declared in the foo function, which are at a different level of scope.
When you enter the program, all the vars declared in main are pushed onto a block of the stack. Same with foo when it is called, but the next block. Then when it reaches the end of the foo function, it pops that set of variables off the stack (or ‘frees’ them). When it reaches the end of the main function, it pops that set of variables off the stack.
So to answer your question, ALL local variables, including local arrays which are stored on the stack, are automatically deleted when they go out of scope. You never have to free those yourself.
You just worry about the stuff that you put on the heap, which is anytime you use “malloc” in C, or “new” in C++.