简体   繁体   中英

Not Printing garbage value

Why the following program is not printing garbage values . As i know , array allocated memory on stack(ie at compile time) and stack memory contain some garbage value . But its not printing garbage values . It is printing 1's . It will print garbage value only when if in function g() , size of array b > size of array a . When size of array in g() > size of array a , then it is printing 12 1's(in this case) and rest as garbage values .

    void f()
    {
        int a[12],i=0;
        for(i=0;i<12;i++)
          a[i]=1;
    }
    void g()
    {
        int b[12],i=0;
        for(i=0;i<12;i++)
          printf("%d\n",b[i]);
    }
    int main()
    {
         f();
         g();
          return 0;
    }

Does the memory allocated to array b is same as the memory allocated to array a previously ?

It IS garbage, left by function f() - and this effect is not defined. The effect is a by-product of how the compiler allocates and deallocates local variables on the stack.

The compiler can produce code to totally overwrites the stack with random data when the function returns, or it can just produce code to modify the stack pointer, which is what it does in this case.

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