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
  • 30,980
  • 23
  • 77
  • 133

4 Answers4

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
  • 196,531
  • 48
  • 417
  • 525
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,562
  • 12
  • 96
  • 109
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
  • 16
  • 22
-1

You did delete it correctly.

Then, you invoked Undefined Behaviour and found the memory still existed(*) and wasn't zeroed - a tool like valgrind would still show it as a bug though, which it is.


(*) By "still existed" I mean "is accessible to the process" - it could contain anything, but happens not to have been overwritten ... yet.

Useless
  • 59,916
  • 5
  • 82
  • 126