一个void函数外释放内存在那里被分配 [英] free memory outside a void function where it is allocated

查看:107
本文介绍了一个void函数外释放内存在那里被分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个void函数

void foo(int *ptr) {
   //trying to allocate memory to hold 5 ints
   ptr = malloc(sizeof(int)*5):
   //I loop ptr and assign each with a value i =0 to 4;
}

在主函数中我有这行

In the main function I have this lines

int main() {
    int *num;
    //I called the function 
    foo(&(num));
    free(num);

   return 1;
}

我得到munmap_chunk()无效指针错误。我曾尝试在更多的信息挖掘,但我无法弄清楚这一点。我知道这将是基本的那些谁在C工作。我在想我是通过引用传递,它应该工作,但事实并非如此。我是新来的C,到目前为止一直是令人头疼。

I get munmap_chunk() invalid pointer error. I did try to dig in more information, but I could not figure this out. I know it will be basic for those who work in c. I was thinking I am passing by reference and it should work, but it is not. I am new to C, and so far has been a headache.

推荐答案

PTR 是一个局部变量,生前与函数结束时,你需要一个指针的指针在为了改变 NUM

ptr is a local variable, his lifetime ends with the function, you need a pointer to pointer in order to alter num in main

   void foo(int **ptr) {
       //trying to allocate memory to hold 5 ints
       *ptr = malloc(sizeof(int)*5);
       //I look ptr and assign each with a value i =0 to 5;
   }

这篇关于一个void函数外释放内存在那里被分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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