为何第二个printf打印垃圾值 [英] why the second printf prints garbage value

查看:151
本文介绍了为何第二个printf打印垃圾值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是源$ C ​​$ C

this is the source code

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

输出 -

35
1637778

第一个printf()打印35,其是K的值,但

the first printf() prints 35 which is the value of k but

在main()的第二个printf打印垃圾值,而不是打印35.why?

In the main() the second printf prints a garbage value rather than printing 35.why?

推荐答案

这里的问题是从乐趣返回一个局部变量的地址返回。该地址是无效的那一刻函数返回。你只是让幸运的第一次调用的printf

The problem here is the return from fun is returning the address of a local variable. That address becomes invalid the moment the function returns. You are simply getting lucky on the first call to printf.

即使当乐趣返回C运行时什么也不做,积极摧毁它的地方在技术上破坏。因此,您第一次使用的*Ĵ工作的是因为本地内存还没有被写入结束。 的printf的的实施虽然可能在写这篇只需在方法利用自身的本地人。因此,在第二次使用你指的是什么地方的printf 使用,而不是 K

Even though the local is technically destroyed when fun returns the C runtime does nothing to actively destroy it. Hence your first use of *j is working because the memory for the local hasn't been written over yet. The implementation of printf though is likely over writing this simply by using its own locals in the method. Hence in the second use of *j you're referring to whatever local printf used and not k.

为了使这项工作,你需要返回指向该生活比乐趣长值的地址。通常,在C中,它与的malloc实现

In order to make this work you need to return an address that points to a value that lives longer than fun. Typically in C this is achieved with malloc

int *fun() {
  int* pValue = malloc(sizeof(int));
  *pValue = 23;
  return pValue;
}

由于的malloc 回归生活,直到调用免费这将是整个<$ C多次使用有效$ C>的printf 。一抓调用函数现在能够告诉程序当它与乐趣的retun完成。要做到这一点调用免费第二次调用的printf

Because the return of malloc lives until you call free this will be valid across multiple uses of printf. The one catch is the calling function now has to tell the program when it is done with the retun of fun. To do this call free after the second call to printf

j=fun();
printf("%d\n",*j);
printf("%d\n",*j);
free(j);

这篇关于为何第二个printf打印垃圾值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆