简体   繁体   English

不打印垃圾值

[英]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 . 它正在打印1。 It will print garbage value only when if in function g() , size of array b > size of array a . 仅当在函数g()中,数组b的大小>数组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 . 当g()中的数组大小>数组a的大小时,它将打印12个1(在这种情况下)并作为垃圾值休息。

    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 ? 分配给数组b的内存是否与先前分配给数组a的内存相同?

It IS garbage, left by function f() - and this effect is not defined. 它是垃圾,由函数f()留下-此效果未定义。 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. 当函数返回时,编译器可以生成代码以用随机数据完全覆盖堆栈,也可以仅生成代码以修改堆栈指针,这就是这种情况。

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

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