“释放的指针未被分配。”在malloc之后出错,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 realloc(points, number*sizeof(point)) } 

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

在这里,我使用malloc初始化points ,后来用realloc改变了它的大小; 那么当我来free时,指针“未分配”怎么样?

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 ,我们不仅可以控制指针指向的位置,还可以控制指针本身的地址。 这允许它移动内存。 句柄是动态管理内存的好方法; 但从概念上讲,指向指针的指针需要一些习惯……

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成功,你不再关心原始指针。 如果必须分配新块,则原始指针无效。 如果它没有,那么它返回相同的指针,你当然不想立即解除分配。

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

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

 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 */ 

}