C Malloc运行时错误

时间:2010-12-15 15:58:34

标签: 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 ;
}

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

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

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

4 个答案:

答案 0 :(得分:11)

你这样做:

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

这是不正确的。您不应该以您使用的方式使用sizeof。你需要:

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

答案 1 :(得分:2)

你为什么要把一个人投入一首歌?

person *personp = (song*) malloc(sizeof(struct person));

答案 2 :(得分:1)

顺便说一句,有一个功能可以做你想做的事情,strdup它不在C标准中,但几乎无处不在,如果不是,最终可以在2个线路中实现。

person *make_person(const char *first, const char *last, const char *location) {
  person *personp = malloc(sizeof(struct person));

  personp->first       = strdup(first); 
  personp->last        = strdup(last);
  personp->location    = strdup(location);
  personp->next_person = NULL;

  return personp ;
}

编辑:我还在函数的签名中添加了const限定符,因为传递的字符串只能被读取而不能被修改。这为将来将使用该功能的程序员提供了更多信息。他会知道他可以安全地传递他的缓冲区和常量字符串而不用担心函数会爆炸。

答案 3 :(得分:0)

施放到person

person *personp = (person *) malloc(sizeof(struct person));

不要sizeof

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

您还需要检查malloc是否成功