小编sub*_*bby的帖子

malloc保留函数调用之间的值

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,但没有找到明确的答案.

c pointers

2
推荐指数
1
解决办法
139
查看次数

标签 统计

c ×1

pointers ×1