c - 为什么在 C 中调用函数后变量的值会丢失?

标签 c pointers memory-leaks

为什么在执行函数“test”后传递的变量“list”为空,即访问列表的元素或释放指针列表会导致内存泄漏?

我错过了什么?

int test(int** container)
{
    int numOfItems = 2;
    int* p1;
    int* p2;
    int j=0;

    container = (int**) malloc (sizeof(int*) * numOfItems);
    for(j=0;j<numOfItems;j++)
         container[j] = (int*) malloc (sizeof(int));

    *(container[0]) = 12;
    *(container[1]) = 13;
}

int main( int argc, const char* argv[] )
{ 
    int* list;
    test(&list);
}

最佳答案

container = (int**) malloc (sizeof(int*) * numOfItems);

应该是

*container = malloc (sizeof(int*) * numOfItems);

container 只是一个局部变量,int* list 的副本。

还有,你一般should not cast malloc 的返回。

关于c - 为什么在 C 中调用函数后变量的值会丢失?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28557907/

相关文章:

java - cpp - 调用基于枚举的函数? (解释或等效的java)

c - 指向结构的数组指针

c# - 理解有漏洞的应用程序的 Performance Profiler 输出?

c - for循环中的内存泄漏

c - C 编程中从单词列表中生成随机单词

c - 如何防止 MMAP 缓存值?

c++ - 我怎样才能指向 vector 元素?

c++ - 有没有一种方法可以使引用成为常量 setter/getter ?

iphone - App delegate 分配的对象显示在多个 subview 中?

c - 为什么我在包含 -lrt 时仍然得到对 timer_create() 的 undefined reference ?