如何在struct中释放指针?

guy*_*bak 1 c struct pointers

这是我的代码:

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);
}
Run Code Online (Sandbox Code Playgroud)

视觉工作室打断了free句子.

我该怎么办?是问题free还是malloc

Spi*_*rix 7

这条线

currBob->name = (char*)malloc(sizeof(char)*strlen(n));
Run Code Online (Sandbox Code Playgroud)

是错的,因为

  1. 您没有包含NUL终结符的空间.
  2. 不应该把结果malloc(和家庭)投在C中.

通过使用来解决问题

currBob->name = malloc(strlen(n) + 1);
Run Code Online (Sandbox Code Playgroud)

如果你想知道我为什么要删除sizeof(char),那是因为sizeof(char)保证是1.所以,没有必要.


作为@EdHeal 在评论中提到,有一个叫功能strdup(),做malloc+ strcpy.它是POSIX功能.如果可用,您可以缩短

currBob->name = malloc(strlen(n) + 1);
strcpy((*currBob).name, n);
Run Code Online (Sandbox Code Playgroud)

currBob->name = strdup(n);
Run Code Online (Sandbox Code Playgroud)

通过使用此功能.另外,请注意

(*currBob).fix = 0;
(*currBob).max = 3;
Run Code Online (Sandbox Code Playgroud)

相当于

currBob -> fix = 0;
currBob -> max = 3;
Run Code Online (Sandbox Code Playgroud)

正如@Edheal 在另一条评论中提到的那样.