I understand that variables declared within a function have automatic storage. Does this mean it's not necessary to free
pointers (p
below) that have been explicitly allocated within a function call using malloc
?
void f() {
int *p;
p = malloc(sizeof(int));
*p = 1;
printf("%p %d\n", p, *p); // 0x7fc135c02850 1
free(p); // is this necessary?
}
int main() {
f();
}
(Note that I used a pointer to an int
here, but the question applies to any pointer that's a return value of malloc
and friends.)
I'm guessing no, since malloc
allocates memory on the heap and not the stack; thus the memory p
points to won't automatically be deallocated when the stack frame for f()
is popped.
p
itself is automatic storage, and it will disappear when the function ends. What it points to however does need to be free()'d
, at some point. For example, you could return the malloc()'d
memory from the function, and free()
it later on - p
has still disappeared
The memory you allocate with malloc()
needs to be free()
'd. In your case, automatic storage applies to the variable p
itself, but not to the memory you allocated! When you use free(p)
, you free the memory p
points to and not the p
variable itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With