简体   繁体   中英

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 . But instead it is printing zero. Why is that? I am using gcc version 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.

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; 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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