malloc保留函数调用之间的值

sub*_*bby 2 c pointers

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);
}
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

我对func()中malloc的行为感到困惑.在第一次调用之后,局部变量指针ptr在堆栈帧中被清除.在第二次调用期间,将在新的堆栈帧中再次创建ptr.所以ptr并没有指向任何地方.那么为什么在第二次调用中打印时,它指向111的内存位置.这可能非常愚蠢.我经常搜索Google,但没有找到明确的答案.

sps*_*sps 5

ptr在为其分配一些值之前,它将具有不确定的值.并且将取消引用具有不确定值的指针undefined behavior,这将导致任何事情 - 包括打印第一次调用中看到的垃圾值func,111在第二次调用中看到的打印func,甚至崩溃程序.

作为旁注,free(ptr);在末尾添加,func以便您的程序释放动态分配的内存malloc.