-3

While I was using delete operator on pointers, I saw something that I could not understand. I think it is best to show it on an example:

#include <iostream>
using namespace std;

int main() {

    int* p = new int[5]{3, 4, 5, 6, 7};

    cout << p[0] << p[1] << p[2] << p[3] << p[4] << '\n';

    delete[] p;

    cout << p[0] << p[1] << p[2] << p[3] << p[4] << '\n';

    return 0;
}

The result:

34567
00567

After the delete operation why first two elements turned to zeros? Thanks for your attention. I’m looking forward to your replies.

dnz2017
  • 11
  • 2
  • That my friend is UB. There is no reason to use deleted pointers. – DimChtz May 12 '18 at 12:21
  • Undefined Behavior means *anything* can happen. Or not. There is no general explanation of the observed behavior in such a case, and although sometimes one can reasonable conclude what's going on under the hood, that's not possible in the current case. – Cheers and hth. - Alf May 12 '18 at 12:21
  • delete operation does not turn elements to zero, it destroys array elements (which is noop in case of `int`) deallocates memory so afterwards those elements become unreachable and deleted pointer value becomes invalid. So the second print run in this case is just a dereferencing of invalid pointer leading to Undefined behavior. – user7860670 May 12 '18 at 12:26
  • @DimChtz Doing so will still lead to UB. – user7860670 May 12 '18 at 12:29
  • 1
    Possible duplicate: https://stackoverflow.com/a/6445794/1968 – Konrad Rudolph May 12 '18 at 12:31
  • This doesn't address the question, but do you really need the extra stuff that `std::endl` does? `'\n'` ends a line. – Pete Becker May 12 '18 at 13:20

4 Answers4

2
 delete[] p;

 cout << p[0] << p[1] << p[2] << p[3] << p[4] << endl;

The moment you use p after calling delete[] on it, it's undefined behavior. As the wording says the behavior is undefined so questioning why x or y happens is pointless as this is uncertain.

Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122
0

You don't want to pay for what you don't need in C++.

Why would you expect released memory to be zeroed? delete just marks the memory as not used anymore, there's no need to zero it since you can't use it anyway without invoking undefined behavior.

Jack
  • 131,802
  • 30
  • 241
  • 343
0

When you 'delete' a pointer or variable, there's no reason for it to be set to '0'.
By deleting the array you simply tell the computer that it can use the given space freely. The interesting question is not why the rest of the values persist, but actually why are the 2 first ones are set to '0', and the answer could really be anything

Wassap124
  • 381
  • 4
  • 14
-1

System do not have to clear this memory with zeroes.

delete[] just means you do not not need this memory anymore and you return this memory to the system. System marked this memory as free and will overwrite it with new data sometime in future.

Oleg Korzhukov
  • 606
  • 6
  • 19