Consider the c code:
void mycode() {
MyType* p = malloc(sizeof(MyType));
/* set the values for p and do some stuff with it */
cleanup(p);
}
void cleanup(MyType* pointer) {
free(pointer);
pointer = NULL;
}
Am I wrong in thinking that after cleanup(p); is called, the contents of p should now be NULL? Will cleanup(MyType* pointer) properly free the memory allocation?
I am coding my college assignment and finding that the debugger is still showing the pointer to have a memory address instead of 0x0 (or NULL) as I expect.
I am finding the memory management in C to be very complicated (I hope that’s not just me). can any shed some light onto what’s happening?
Yes that will free the memory correctly.
pointerinside the cleanup function is a local variable; a copy of the value passed in stored locally for just that function.This might add to your confusion, but you can adjust the value of the variable
p(which is local to themycodemethod) from inside thecleanupmethod like so:In this case,
pointerstores the address of the pointer. By dereferencing that, you can change the value stored at that address. And you would call thecleanupmethod like so:(That is, you want to pass the address of the pointer, not a copy of its value.)
I will note that it is usually good practice to deal with allocation and deallocation on the same logical ‘level’ of the software – i.e. don’t make it the callers responsibility to allocate memory and then free it inside functions. Keep it consistent and on the same level.