void func(){
int *ptr;
printf("\n *** %d\n",*ptr);
ptr=malloc(sizeof(int));
*ptr=111;
printf("\n ##### %d\n",*ptr);
}
int main()
{
func();
func();
return(0);
}
GCC 中的输出
*** -1991643855 // Junk value for the first call
##### 111 // After allocating and assigning value
*** 111 // second call pointer the value which 111
##### 111 // second call after assigning
我对 func() 中 malloc 的行为感到困惑。第一次调用后,局部变量指针 ptr 在堆栈帧中被清除。在第二次调用期间,在新的堆栈帧中再次创建 ptr。所以 ptr 没有指向任何地方。那么为什么在第二次调用时打印它时,它指向 111 的内存位置。这可能很愚蠢。我用谷歌搜索了很多但没有找到明确的答案。
最佳答案
ptr
在被赋值之前会有不确定的值。取消引用具有不确定值的指针将调用未定义的行为
,这可能导致任何结果——包括打印垃圾值,如您第一次调用 func
时看到的,打印 111
,如您第二次调用 func
时所见,甚至导致您的程序崩溃。
作为旁注,在 func
的末尾添加 free(ptr);
以便您的程序释放使用 malloc
动态分配的内存.
关于c - malloc 在函数调用之间保留值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38910419/