0

the following is the code where I stored integers on heap and then deleted them using delete[]

int main(){

size_t n{20};
int *a =new int[n];
for (size_t i=0;i<n;i++)
{
    a[i]=i;
}

delete[] a;

for (size_t k=0;k<n;k++)
{
    cout<<a[k]<<" ";
}
}

The output to this shows that only the first two elements of the dynamically created array have been cleared while the rest still retain their values. Why don't all indices contain garbage value?

Output of this code: 8130008 8131488 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

anonymous38653
  • 393
  • 4
  • 16
  • 3
    `delete[]` doesn't mean the data disappears or goes bad. It means that you no longer can safely access that area of memory. – PaulMcKenzie Apr 10 '20 at 18:26
  • 5
    "I sold my house to someone else, but when I drove there last night, it was still there." I know this a silly metaphor, but it applies. It is still illegal to enter said house because it isn't yours. It might not be there tomorrow, or next week, or next year. It isn't up to you what the new owner does with the house (memory) that is no longer yours. – MPops Apr 10 '20 at 18:27
  • 3
    Accessing a dynamically allocated object after it is deleted is **Undefined Behavior**. Anything is acceptable and no explanations about why things happen should be expected. – Thomas Matthews Apr 10 '20 at 18:27
  • 3
    How about, "My driver's license was taken away from me, but I was able to drive a car and not get stopped by a policeman". Just because you drove a car and was not stopped doesn't mean what you did was legal. Tomorrow you could get stopped, next week, maybe you can drive like that for years and nothing happening. Just consider yourself lucky. – PaulMcKenzie Apr 10 '20 at 18:29
  • 1
    thanks everyone, I got the point – anonymous38653 Apr 10 '20 at 18:30
  • 2
    "My code has a bug. Why does it do weird things?" Umm, because it has a bug. If your code can do weird things after you fix the bug, then you have a mystery. – David Schwartz Apr 10 '20 at 18:31
  • @MPops your answer is wonderful man ! – anonymous38653 Apr 10 '20 at 18:35
  • @PaulMcKenzie thanks !! – anonymous38653 May 20 '20 at 18:27

0 Answers0