c - 正在重新分配的指针未分配

标签 c malloc realloc

我正在尝试动态分配一个结构数组,但每当我运行程序时,我都会不断收到:a.out(6487,0x7fff7ecb8300) malloc: * error for object 0x7fff6f670000: pointer being realloc'd was not allocated * 在malloc_error_break 设置断点调试

struct node {
    char course[25];
    char category[20];
    char prereq[50];
    char notes[50];
};



int main(int argc, char* argv[])
{
    FILE *fp;
    char *filename = argv[1];
    char *token;

    char buffer[100];
    char *del = ",\n";
    int num = 5, i = 0, j =0, count = 0;
    struct node *d = malloc(num * sizeof(struct node));
    char** complete = malloc(num * sizeof(char*));
    printf("%s\n", filename);


    if( (fp = fopen(filename, "r")) == NULL )
    {
        printf("unable to open %s\n", filename);
        exit(1);
    }
    while(fgets(buffer, sizeof(buffer), fp) != NULL)
    {

        if(count == num)
        {
            num = num + 5;
            struct node *d = realloc(d, sizeof(d)*num);
            printf("Reallocating\n");
        }  
        token = strtok(buffer, del);

        if(strncmp(token, "#", 1) != 0)
        {   

            strcpy(d[count].course, token);
            printf("%s\n", d[count].course);
            strcpy(d[count].category, strtok(NULL, del));
            printf("%s\n", d[count].category);
            strcpy(d[count].prereq, strtok(NULL, del));
            printf("%s\n", d[count].prereq);
            strcpy(d[count].notes, strtok(NULL, del));
            printf("%s\n", d[count].notes);
            count++;
        }


    }

最佳答案

struct node *d = realloc(d, sizeof(d)*num);

您声明了一个新的 d 变量,它覆盖了前一个变量,并将其尚未初始化的值提供给 realloc

你需要这样做:

struct node *newD = realloc(d, num * sizeof *d);
if(!newD) {
    // Allocation failure, do something about it and break out
} /* else */
d = newD;

另请注意,我更正了 sizeof,它测量的是指针的大小,而不是指针的大小。

关于c - 正在重新分配的指针未分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30048220/

相关文章:

c - 使用 Pebble iOS Kit 获取 Pebble 应用程序元数据的正确方法

c - 如何释放已分配的 char 指针? (我将char指针设置为NULL)

c - 将分配的值存储到分配的数组

C 编程 - printf 语句给出 "expression expected"错误

c - C中的暂停功能不响应回车键

c - 在结构中使用指针数组重新分配

c - c中共享内存的重新分配

c - 为什么总是显示错误:pointer being realloc'd was not allocated

c - 如何转换字符串以便可以将字符串读取为十六进制值?

c - 关于string和char的面试题