如何释放结构中的指针?

How to free a pointer in struct?

这是我的代码:

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 在 free 句子处中断。

我该怎么办? freemalloc 有问题吗?

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

是错误的,因为

  1. 您没有为 NUL 终止符包含 space。
  2. should not cast the result of malloc(and family)在C.

使用

解决问题
currBob->name = malloc(strlen(n) + 1);

如果您想知道为什么我删除了 sizeof(char),那是因为 sizeof(char) 保证为 1。因此,没有必要。


正如 @EdHeal ,有一个名为 strdup() 的函数可以执行 malloc+strcpy。它是 POSIX 函数。如果可用,您可以缩短

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

currBob->name = strdup(n);

通过使用这个功能。另外,请注意

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

等同于

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

作为@Edheal .