Question

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 ?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top