这是我的代码:
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);
}
视觉工作室打断了free句子.
我该怎么办?是问题free还是malloc?
这条线
currBob->name = (char*)malloc(sizeof(char)*strlen(n));
是错的,因为
malloc(和家庭)投在C中.通过使用来解决问题
currBob->name = malloc(strlen(n) + 1);
如果你想知道我为什么要删除sizeof(char),那是因为sizeof(char)保证是1.所以,没有必要.
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;