"指针被释放没有被分配&QUOT。之后的malloc,realloc的错误 [英] "Pointer being freed was not allocated." error after malloc, realloc

查看:127
本文介绍了"指针被释放没有被分配&QUOT。之后的malloc,realloc的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的错误有以下code:

I have this error with the following code:

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))
}

我寻觅,却发现只是例子,很明显,没有分配。

I have searched, but found only examples where it was clear there was no allocation.

在这里,我用的malloc 来初始化,后来改变了它的尺寸 realloc的;因此,如何指针不分配当我来到免费呢?

Here, I used malloc to initialise points, and later changed its size with realloc; so how is the pointer "not allocated" when I come to free it?

推荐答案

的realloc 可移动存储到新的位置(如果没有足够的空间来扩大老指针)。如果出现这种情况,你需要释放新的指针。

realloc may move the memory to a new location (if there is not enough space to expand the old pointer). If that happens, you need to free the new pointer.

试试这个调整:

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 ,我们给它不仅在在指针所指向的地方控制,但地址指针本身。这使得它可以左右移动的存储器。句柄是动态内存管理的好办法;但在概念的指针的指针需要一些时间来适应......

By passing a handle to other_stuff, we give it control not only over the place where the pointer is pointing, but to the address of the pointer itself. This allows it to move the memory around. Handles are a good way to manage memory dynamically; but conceptually a pointer to a pointer takes some getting used to...

这篇关于"指针被释放没有被分配&QUOT。之后的malloc,realloc的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆