gpt4 book ai didi

c - malloc、realloc 后出现 "Pointer being freed was not allocated."错误

转载 作者:太空狗 更新时间:2023-10-29 14:55:02 26 4
gpt4 key购买 nike

我有以下代码的错误:

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

关于c - malloc、realloc 后出现 "Pointer being freed was not allocated."错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20578340/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com