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.
The need to free()
doesn't depend on whether or not you've declared a pointer, but rather whether or not you've malloc()
ed memory.
Like Brian Bondy said before, variables ("int number
", "char string[10]
", "float your_boat
", etc.) go away when then fall out of scope, like when your code leaves a function block. So the pointer in your question ("temp
") doesn't go away when you call free()
-- rather, whatever your code allocated when it called malloc()
goes away. Your pointer still stays there, i.e. immediately after your example code you could say "temp = &some_other_variable
" without having to say (again) "int *temp;
".
If somebody ever implemented a function, that they also happened to call malloc()
, that would claim memory for your program, and that did not require you to release that data, then you would be able to say
int * temp = (int*)malloc(sizeof(int));
without later saying
free(temp);
But that's not the way malloc()
is implemented.