为何第二个printf打印垃圾值

编程入门 行业动态 更新时间:2024-10-27 20:32:47
本文介绍了为何第二个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 回归生活,直到调用免费这将是整个的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打印垃圾值

本文发布于:2023-07-29 08:20:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1239021.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:第二个   垃圾   printf

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!