Why do I have to use free() when I declare a pointer such as:
int *temp = (int*)malloc(sizeof(int))
*temp = 3;
but not when I do:
Alnitak is correct. I'd like to point out what "on the stack" really means.
When a program makes a function call, it expects the function to do some amount of work, then return and continue to the next line of code. The function has no way of knowing where to return when the function is complete. So, the machine has a call stack for each program used to push the address of the following statement in the program before calling the function. The "return" statement simply pops the program address and jumps to it.
The stack is also a handy scratch pad of temporary space. It is possible to write into unused areas of the stack. Declaring a local variable inside a C function does exactly this. When the function returns, the stack does not need to be cleaned up, freed, or otherwise processed because it was just a temporary space anyway and now goes out of scope.
In contrast, calling malloc()
allocates memory from the heap, which explicitly sets aside memory for the program and remains in scope for as long as the program is running. Thus, if you don't free()
the memory, it will remain allocated and considered a memory leak.