so I'm trying to understand the whole concept of memory management in C and I was given this code:
int main(int argc, int *argv[]) {
item *x = NULL;
x = (item *) malloc (sizeof(item));
...
free_item(&x);
}
void free_item(item **x) {
free(*x);
*x = NULL;
}
where item
is earlier defined structure. The point, where I get confused is free_item(&x);
because when I write free_item(x);
and change the function to:
void free_item(item *x) {
free(x);
x = NULL;
}
the code seems to work the same way as the previous one.
So, is there any difference? And if not, is there any reason, why would someone send an adress on a pointer of a structure to a function, which frees this structure?
Yes. First, I think there's a typo in your modified function. It should be:
void free_item(item *x) {
free(x);
x = NULL;
}
Now, for the differences. The free
call will succeed, as all it expects is a "pointer-to-type" variable for data which is allocated dynamically on the heap.
The second part, x = NULL
, will not work as expected. Remember, in C, when passing an argument to a function, we pass by value always, never by reference. You are being passed a copy of a variable, so x = NULL
just sets a temporarily automatically allocated copy of x
to NULL
, not the actual variable passed as an argument.
The original function which you changed does both parts correctly.
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