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
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.
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;
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.