Peter
Peter

Reputation: 419

Pointers - deletion

I started learning C++ on my own 2 weeks ago and now I'm studying about pointers. Why the following code doesn't work the way I expect and after deletion I see the same values in the array. I thought the array would be deleted and the pointer will point to some random integer in the heap, unless I write dArray = NULL. Could somebody elaborate on this a little bit, please? I don't know what I'm doing wrong. Thanks.

PS: I use Xcode on Mac.

Code:

#include <iostream>
using namespace std;


int main() {

    int *dArray = new int[5];

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

    cout << "Show array:" << endl;
    for(int i=0; i<5; i++) {
        cout << dArray[i] << endl;
    }

    delete [] dArray;

    // show array after deletion
    cout << "After deletion:" << endl;
    for(int i=0; i<5; i++) {
        cout << dArray[i] << endl;
    }

    return 0;
}

The output:

Show array:
0
2
4
6
8
After deletion:
0
2
4
6
8
Program ended with exit code: 0

Upvotes: 2

Views: 92

Answers (3)

murison
murison

Reputation: 3985

The name "delete" may be a bit misleading. It does not actually delete anything - just deallocates previously allocated memory AND calls the destructor of the object that it was pointing to (if one does exist). Calling the destructor is the main difference between delete and free.

Upvotes: 1

John3136
John3136

Reputation: 29266

delete doesn't change the value of the pointer. It just means what the pointer is pointing to isn't legal to access anymore (gives undefined behavior).

In a lot of cases (like yours) the program may look like it works, but change something (like adding another new) and it will fail in weird and hard to trace ways... Setting the pointer to 0 after deletion at least makes the failures easier to identify.

Upvotes: 4

Axel
Axel

Reputation: 14169

Deleting the array just gives the memory back to the runtime, but does not overwrite it. You may not use it any more, and doing so invokes undefined behaviour.

Upvotes: 1

Related Questions