简体   繁体   中英

How to free a pointer in struct?

This is my code:

typedef struct bobTheBuilder{
    char *name;
    int fix;
    int max;
};

int main(void){

    struct bobTheBuilder bob;
    initBob(&bob);
    del(&bob);

    system("PAUSE");
    return (0);
}

void initBob(struct bobTheBuilder *currBob)
{
    char *n="bob";
    currBob->name = (char*)malloc(sizeof(char)*strlen(n));
    strcpy((*currBob).name, n);
    (*currBob).fix = 0;
    (*currBob).max = 3;
}

void del(struct bobTheBuilder *currBob)
{
    free(currBob->name);
}

Visual studio breaks at the free sentence.

What should i do? Is the problem with the free or the malloc ?

The line

currBob->name = (char*)malloc(sizeof(char)*strlen(n));

is wrong because

  1. You did not include the space for the NUL-terminator.
  2. You should not cast the result of malloc (and family) in C.

Fix the problems by using

currBob->name = malloc(strlen(n) + 1);

If you are wondering why I've removed sizeof(char) , it is because sizeof(char) is guarenteed to be 1. So, it is not necessary.


As @EdHeal mentions in a comment , there is a function called strdup() that does malloc + strcpy . It is POSIX function. If it is available, you can shorten

 currBob->name = malloc(strlen(n) + 1); strcpy((*currBob).name, n); 

to

 currBob->name = strdup(n); 

by using this function. Also, note that

 (*currBob).fix = 0; (*currBob).max = 3; 

is equivalent to

 currBob -> fix = 0; currBob -> max = 3; 

as @Edheal mentions in another comment .

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