简体   繁体   中英

Freeing struct that cointains double pointer

Say I have a struct defined as follows:

typedef struct {
int width;
int height;
char **data;
} puzzle;

Then, according to my textbook, the free function should look like this:

void puzzle_free(puzzle** puzzle) 

But I don't see why puzzle should be a double pointer in the free function.

Well that depends. If you did this,

puzzle **a = malloc(sizeof *a * NUMITEMS);
for(size_t i = 0; i < NUMITEMS; i++)
   a[i]= malloc(sizeof *a[i] * NUMITEMS);

Then ofcourse free can be like this. myfree(&puzzle); - signature being myfree(puzzle *** a) .

Then if you had simply this,

puzzle* a = malloc(sizeof *a *NUMITEMS);

Then myfree(&a) (signature containing double pointer) would suffice. It depends on the what you are trying to free.

void myfree(puzzle **a){
    free(*a);
}

The way the book mentioned - it is safe to say that book used the kind of allocation shown in the second above. You have to pass the address of it because otherwise you will be making changes to a local variable. (This is why the double pointer is needed as mentioned by book).

It probably has nothing to do with the double pointer contained in the struct, but is just a way to write free functions that helps prevent access after free.
Eugene Sh. refers to it in his comment.

The implementation of puzzle_free would be:

void puzzle_free(puzzle** puzzle_p) {
    puzzle *puzzle = *puzzle_p
    // Somehow free puzzle->data
    free(puzzle);
    *puzzle_p = NULL;
}

And usage would be:

puzzle *puzzle = malloc(...)
// Fill it, use it.
puzzle_free(&puzzle);
// puzzle pointer is now NULL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM