我有以下代码片段:
typedef struct person {
char *first ;
char *last ;
char *location ;
struct person *next_person ;
} person ;
person *make_person(char *first, char *last, char *location) {
person *personp = (person*) malloc(sizeof(struct person));
personp->first = (char*) malloc(sizeof(strlen(first) + 1));
personp->last = (char*) malloc(sizeof(strlen(last) + 1));
personp->location = (char*) malloc(sizeof(strlen(location) + 1));
strcpy(personp->first, first);
strcpy(personp->last, last);
strcpy(personp->location, location);
personp->next_person = NULL;
return personp ;
}
当我将它与我的其余代码集成时,它开始执行,然后继续前进。
*** glibc detected *** ./level1: free(): invalid next size (fast): 0x0804a188 ***
知道出了什么问题吗?我感觉这与我的 malloc 有关。
最佳答案
你这样做:
personp->first = (char*) malloc(sizeof(strlen(first) + 1));
这是不正确的。您不应该像以前那样使用 sizeof
。你需要:
personp->first = malloc(strlen(first) + 1);
关于C Malloc 运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4451979/