在空间函数之外的空闲内存,它被分配

我有一个无效function

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

在主要function我有这条线

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

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

ptr是一个局部变量,他的生命周期以函数结束,你需要一个指向指针的指针才能改变main num

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

对于初学者来说,函数foo被声明为

 void foo(int *ptr); ^^^^^^^^ 

这是它的参数类型为int * 。 当你调用函数时

 foo(&(num)); ^^^^^^ 

其参数的类型为int **因为变量num被声明为

 int *num; 

编译器至少应发出类型不兼容的消息。

您需要按以下方式定义函数

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

在这种情况下,函数调用将是正确的,并且当原始指针通过引用传递时,它将在调用函数后更改。

至于原始的function定义

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

那么它的参数是函数的局部变量,它保存参数的副本。 对原始参数副本的局部变量的任何更改都不会影响原始指针本身。 退出函数后,将破坏局部变量(参数) ptr