【问题标题】:pointer being realloced was not allocated重新分配的指针未分配
【发布时间】:2015-07-14 21:45:30
【问题描述】:

我正在尝试动态分配一个结构数组,但每当我运行程序时,我都会不断收到:a.out(6487,0x7fff7ecb8300) malloc: * error for object 0x7fff6f670000: pointer being realloc'd was not assigned * 在 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++;
        }


    }

【问题讨论】:

  • 在使用argv[1]之前,检查是否argc==2。只是一个建议。
  • 警告:当在malloc(等)you should always write it 中以ptr = malloc(sizeof(*ptr) * ...); 而不是ptr = malloc(sizeof(ptrtype*) * ...); 调用sizeof
  • 因此struct node *d = realloc(d, sizeof(d)*num); 是错误的:这应该使用sizeof(*b) 而不是sizeof(b)

标签: c malloc realloc


【解决方案1】:
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,它测量的是指针的大小,而不是指针的大小。

【讨论】:

  • 谢谢!这解决了一切!
【解决方案2】:

在:

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

这声明了一个新变量d,其初始值未确定,并将其传递给realloc。将其更改为:

struct node *tmp = realloc(d, sizeof(*d)*num);
if(!tmp)
    ; // handle error
d = tmp;

【讨论】:

  • 这不是分配sizeof (any pointer)吗?我希望在那里有sizeof(struct node)
  • @Jongware 我更正了,但没有提及,希望读者注意。
猜你喜欢
  • 1970-01-01
  • 2012-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-13
  • 2016-01-08
  • 1970-01-01
相关资源
最近更新 更多