【问题标题】:Why are the values of a variable lost after a function call in C?为什么在 C 中调用函数后变量的值会丢失?
【发布时间】:2015-02-17 08:48:38
【问题描述】:

为什么在执行函数“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);
}

【问题讨论】:

    标签: c pointers memory-leaks


    【解决方案1】:
    container = (int**) malloc (sizeof(int*) * numOfItems);
    

    应该是

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

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

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

    【讨论】:

      猜你喜欢
      • 2012-04-18
      • 1970-01-01
      • 2018-02-05
      • 2014-11-26
      • 2020-12-19
      • 2014-08-23
      • 1970-01-01
      • 1970-01-01
      • 2019-12-09
      相关资源
      最近更新 更多