0

Possible Duplicate:
C++ delete - It deletes my objects but I can still access the data?
Why doesn't delete destroy anything?

I've Created dynamic array, and I added values ​​to the values ​​of the array like that.

int *pArr;
pArr = new int[10];

for(int i=0;i<10;i++){
   pArr[i] = i+2;
}

delete[] pArr;  

// After deletion I can find the value of the array items.
cout << pArr[5] << endl;

As you see in the code above and in the last line, I can output the fifth element in the array without any problem . With that supposed to be the array has been removed.

Community
  • 1
  • 1
Lion King
  • 32,851
  • 25
  • 81
  • 143

3 Answers3

1

Once you delete[] the array and still try to access the elements of the array it is Undefined Behavior and any behavior is possible.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
1

To show that the memory can be used again, consider this expansion of your code:

int *pArr;
pArr = new int[10];

for(int i=0;i<10;i++){
       pArr[i] = i+2;
}

delete[] pArr;

int *pArr2;
pArr2 = new int[10];

for(int i=0;i<10;i++){
       pArr2[i] = (2*i)+2;
}

cout << pArr[5] << endl;

That prints out 12 for me. i.e. the value from pArr2[5] actually. Or at least I should say it does for my machine with my specific compiler & version, etc. As others have pointed out it is undefined behaviour. But hopefully my example shows you at least one kind of undefined behaviour.

mattjgalloway
  • 34,792
  • 12
  • 100
  • 110
0

Yes, this may work, but is not guaranteed to work. Delete [] only invalidates the memory but does not zero it. The memory you are referencing is invalidate at this point. So don't do it :)

Tobias Schlegel
  • 3,970
  • 18
  • 22