Search code examples
cmallocruntime-errordynamic-memory-allocation

C Malloc Run-time Error


I've got the following snippet of code:

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

When I integrate it with the rest of my code, it begins executing, then proceeds go ballistic.

*** glibc detected *** ./level1: free(): invalid next size (fast): 0x0804a188 ***

Any idea what's going wrong? I have a feeling it has to do with my malloc.


Solution

  • You do:

    personp->first = (char*) malloc(sizeof(strlen(first) + 1));
    

    which is incorrect. You should not be using sizeof the way you've used. You need:

    personp->first = malloc(strlen(first) + 1);