这是我的代码:
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
?
这条线
currBob->name = (char*)malloc(sizeof(char)*strlen(n));
Run Code Online (Sandbox Code Playgroud)
是错的,因为
malloc
(和家庭)投在C中.通过使用来解决问题
currBob->name = malloc(strlen(n) + 1);
Run Code Online (Sandbox Code Playgroud)
如果你想知道我为什么要删除sizeof(char)
,那是因为sizeof(char)
保证是1.所以,没有必要.
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)
归档时间: |
|
查看次数: |
239 次 |
最近记录: |