The correct way to free memory in C

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 itemis the previously defined structure. The point where they confuse me 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 works the same as the previous one.

So is there any difference? And if not, is there some reason why someone sends an address to a structure pointer to a function that frees this structure?

+4
source share
5 answers

Yes. First, I think there is a typo in your modified function. It should be:

void free_item(item *x) {
  free(x);
  x = NULL;
}

, . free , , , " " , .

x = NULL . , C, , , . , x = NULL x NULL, , .

, , .

+3
  • , content x, . &x free() memeory, main(). .

  • - x free_item(), x, main(). x = NULL; free_item().

0

free_item ( item **x).

(main::x) free_item::x ( ), NULL ( ).

printf("%p\n", x); main() ( free_item).

NULL x - , .

, , 0x00400000, , 0x00410000.

0x00400000 0x00410000 <- x is stored here
0x00400004 0x00400000 <- tmp described later; point to x
...
0x00410000 .......... <- x points here; start of item - returned by malloc

item **tmp = &x, , 0x00400000 ( tmp ).

free_item():

free(*tmp);     // The same as free(0x00410000)
*tmp = NULL;    // Modifies data at 0x00400000 = NULL
0

, , .

,

 item *x

free(x)
-1
  • x = (item *) malloc (sizeof(item)); . x = malloc(sizeof(item)); .

2.

void free_item(item *data){
  free(data);
}

.

  1. Write the idiomatic code C. There is no difference, but it is difficult to debug and maintain.

I would write free_item(x);, but not free_item(&x)havefree_item(item **x)

-2
source

All Articles