C Malloc 运行时错误

标签 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 有关。

最佳答案

你这样做:

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

这是不正确的。您不应该像以前那样使用 sizeof。你需要:

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

关于C Malloc 运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4451979/

相关文章:

c - GDAL 1.11 不支持 vector ?

c - 如何传递没有静态顺序的数组? C语言

c - 使用链表 IN C 表示和排序多项式

c - 重新分配一个数组但不要丢失其中的元素

c - C 中的运行时错误 (CodeChef)

c - 如何找到st_link的偏移量?

c - 释放 C 中结构的内存数组

c - 在C中为结构中的数组分配顺序内存地址

C : Runtime Error Verdict (Help debugging)

mysql - 添加数据库时出现逻辑错误