“没有分配被释放的指针。” malloc之后的错误,realloc

时间:2013-12-14 00:36:52

标签: c pointers dynamic-arrays

我在以下代码中出现此错误:

int main(){
    point   *points = malloc(sizeof(point));
    if (points == NULL){
        printf("Memory allocation failed.\n");
        return 1;
    }
    other_stuff(points);
    free(points);
    return 0;
}
void other_stuff(point points[]){
    //stuff
    realloc(points, number*sizeof(point))
}

我搜索过,但只找到了很明显没有分配的例子。

在这里,我使用malloc初始化points,后来用realloc更改了其大小;那么当我来到free时,指针“未分配”是怎么回事?

3 个答案:

答案 0 :(得分:8)

realloc可能会将内存移动到新位置(如果没有足够的空间来扩展旧指针)。如果发生这种情况,您需要释放新指针。

试试这个调整:

int main(){
    point   *points = malloc(sizeof(point));
    if (points == NULL){
        printf("Memory allocation failed.\n");
        return 1;
    }
    other_stuff(&points);
    free(points);
    return 0;
}
void other_stuff(point **points){
    //stuff
    point *temp = realloc(*points, number*sizeof(point));
    if(temp != NULL) {
      *points = temp;
      // and do your stuff
    }
    else {
      // panic? memory reallocation failed. Deal with it gracefully.
    }
}

通过将句柄传递给other_stuff,我们不仅可以控制指针指向的位置,还可以控制指针本身的地址。这允许它移动内存。句柄是动态管理内存的好方法;但从概念上讲,指向指针需要一些人习惯...

答案 1 :(得分:2)

realloc返回一个新指针。如果函数成功,那个就是你需要释放(最终)的东西。否则,它会失败,并且你会保留旧指针。

如何使用realloc

whataver *f = malloc(count * sizeof(*f));
/* ... */
whatever *temp = realloc(f, new_count * sizeof(*temp));
if (temp)
    f = temp;  // realloc worked, f is no longer valid/needed
else
    free(f);   // error

realloc可能会返回相同的指针,也可能不会。关键是如果realloc成功,你不再关心原始指针。如果必须分配新块,则原始指针无效。如果没有,那么它返回相同的指针,你当然不想立即解除分配。

答案 2 :(得分:0)

谢谢您的解决方案:realloc(MAY)返回一个NEW指针。

此外,我相信以下内容可能会有所帮助:

int main(){
    point   *points = malloc(sizeof(point));
    if (points == NULL){
        printf("Memory allocation failed.\n");
        return 1;
    }
    other_stuff(&points); /* Send address of points */
    free(points);
    return 0;
}
void other_stuff(point (*ppoints)[]){
    //stuff
    realloc(*ppoints, number*sizeof(point))  /* If a new storage area is assigned by     realloc the original points location will be updated in main */

}