为什么第二个printf打印垃圾值

1 c garbage

这是源代码

#include <stdio.h>
#include <stdlib.h>

int *fun();

int main()
{  
    int *j;
    j=fun();
    printf("%d\n",*j);
    printf("%d\n",*j);
    return 0;
}

int *fun()
{
    int k=35;
    return &k;
}
Run Code Online (Sandbox Code Playgroud)

输出 -

35
1637778
Run Code Online (Sandbox Code Playgroud)

第一个printf()打印35,这是k的值

在main()中,第二个printf打印垃圾值而不是打印35.为什么?

Jar*_*Par 5

这里的问题是返回从fun返回局部变量的地址.函数返回时该地址变为无效.你第一次打电话的时候很幸运printf.

即使本地在fun返回时在技术上被破坏,C运行时也无法主动销毁它.因此,你的第一次使用*j有效的,因为本地的内存尚未被写入.虽然实现printf可能只是通过在方法中使用自己的locals来编写它.因此,在第二次使用时,*j你指的是当地printf使用的和不使用的k.

为了完成这项工作,您需要返回一个指向寿命超过的值的地址fun.通常在C中,这是通过实现的malloc

int *fun() {
  int* pValue = malloc(sizeof(int));
  *pValue = 23;
  return pValue;
}
Run Code Online (Sandbox Code Playgroud)

因为malloc直到你打电话给你的生命回归free将在多次使用时有效printf.一个问题是调用函数现在必须告诉程序何时完成重新调整fun.要做到这一点调用free第二次调用后printf

j=fun();
printf("%d\n",*j);
printf("%d\n",*j);
free(j);
Run Code Online (Sandbox Code Playgroud)