C Malloc运行时错误

Mik*_*ike 1 c malloc runtime-error dynamic-memory-allocation

我有以下代码片段:

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 ;
}
Run Code Online (Sandbox Code Playgroud)

当我将它与我的其余代码集成时,它开始执行,然后继续弹道.

*** glibc detected *** ./level1: free(): invalid next size (fast): 0x0804a188 ***
Run Code Online (Sandbox Code Playgroud)

知道出了什么问题吗?我觉得它与我的malloc有关.

cod*_*ict 11

你做:

personp->first = (char*) malloc(sizeof(strlen(first) + 1));
Run Code Online (Sandbox Code Playgroud)

哪个不对.你不应该使用sizeof你使用的方式.你需要:

personp->first = malloc(strlen(first) + 1);
Run Code Online (Sandbox Code Playgroud)