1

Consider the program below.

# include <iostream>

int main()
{
    int* arr{new int[3]{9, 8, 7}};
    std::cout << arr[67];
}

Why does this program always print 0 in my machine? Shouldn't this print some garbage value instead? As dynamic arrays are almost identical to fixed arrays.

SuperNoob
  • 170
  • 1
  • 10
  • 3
    Undefined behaviour is [undefined](https://stackoverflow.com/questions/56979248/why-does-this-simple-program-result-in-puppies-puppies-puppies-to-the-console). But in your case it might be because the pages are zeroed-out and you are lucky that `arr[67]` still belong to you. – Quimby Feb 20 '21 at 13:59
  • @Quimby So that's it? No any other reason? – SuperNoob Feb 20 '21 at 14:01
  • 1
    @SuperNoob The value that get printed (or indeed if any value gets printed at all) is **undefined**. A crash would also be possible. – john Feb 20 '21 at 14:02
  • 1
    ***Shouldn't this print some garbage value instead?*** An OS may 0 the memory pages handed to your application the first time to avoid information leaking from the previous application that used the same memory. This zeroing is a OS feature and only happens the first time the OS gives a page to your process. Your process can allocate and free from this or more pages it receives without giving the page back to the OS so the second time it may not be 0. In either case it is undefined behavior what actually happens. – drescherjm Feb 20 '21 at 14:05

0 Answers0