简体   繁体   English

为什么printf不打印垃圾值?

[英]Why printf is not printing garbage value?

#include<stdio.h>

void foo(){
  int i;
  printf("%d\n",i);  //should print garbage value
}

void main(){
  foo();
}

foo should print garbage value of i . foo应该输出i垃圾值。 But instead it is printing zero. 而是打印零。 Why is that? 这是为什么? I am using gcc version 4.9.2. 我正在使用gcc版本4.9.2。

Your program demonstrates undefined behaviour, so it's a mistake to have any expectations; 您的程序表现出不确定的行为,因此有任何期望都是错误的。 it's perfectly valid for it to print zero here. 在这里打印零是完全有效的。

In fact, this is not terribly unexpected. 实际上,这并非出乎意料。 When your program starts all its memory contains nothing but zero (this depends on your OS, of course, but is probably true), so when you extend your stack into that space, or allocate heap memory for the first time, then you will get zero values. 当程序启动时,其所有内存仅包含零(当然,这取决于您的操作系统,但这可能是正确的),因此,当您将堆栈扩展到该空间或第一次分配堆内存时,您将得到零值。

As a (non-trivial) program runs it extends and shrinks the stack, allocates and frees parts of the heap, and gradually the memory collects lots of non-zero garbage. 当(非平凡的)程序运行时,它会扩展和缩小堆栈,分配和释放堆的一部分,然后内存逐渐收集大量非零垃圾。 If you had called foo() as part of a real project you might expect that garbage value to vary through time. 如果您将foo()作为真实项目的一部分进行了调用,则您可能希望该垃圾值会随时间变化。

Of course, in your trivial example, an optimizing compiler will probably notice that the value is uninitialized, emit a warning, and not bother loading anything from memory, in which case your garbage value may come from a register. 当然,在您的琐碎示例中,优化的编译器可能会注意到该值未初始化,会发出警告,并且不会从内存中加载任何内容,在这种情况下,您的垃圾值可能来自寄存器。 The chances of this being zero are now dependent on the context in which foo() is called; 现在,该可能性为零的可能性取决于调用foo()的上下文。 if the caller uses a zero for something, you might find that a call from that site will always print zero. 如果呼叫者对某事使用零,则可能会发现来自该站点的呼叫将始终显示零。

In summary, undefined behaviour is undefined, and might vary over the runtime of a program, and may vary between compilers, between compiler optimization levels, and might change when apparently unrelated code is adjusted. 总而言之,未定义的行为是未定义的,并且可能会在程序的运行时中发生变化,并且可能在编译器之间,编译器优化级别之间发生变化,并且在调整了明显无关的代码时可能会发生变化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM