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