DMA using new[] and delete[]

I've been trying to get the hang of dynamically allocated memory in C++. To test things, I created a simple program that dynamically allocates an array, assigns values to it and prints it, deletes it and then prints it again. I did this expecting the program to crash the second time it tried to print the values, but in fact it prints out the correct sequence of values again just fine. I find this puzzling as I thought the pointer should no longer point to the addresses of these values after using delete[].

Any ideas why this is happening?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>

using namespace std;

int main()
{
    int *ptr = new int[5];

    cout << "Before deleting array:\n";

    for(int i = 0; i < 5; ++i)
    {
        *(ptr + i) = i + 1;
        
        cout << *(ptr + i) << endl;
    }

    delete[] ptr;

    cout << "\nAfter deleting array:\n";

    for(int i = 0; i < 5; ++i)
    {
        *(ptr + i) = i + 1;
        
        cout << *(ptr + i) << endl;
    }

    return 0;
}
Trying to deference a deleted array is undefined behavior - it could work, or it could cause your program to do anything else. The delete/delete[] operation basically tells your Operating System that its okay to reallocate the freed memory somewhere else, but the OS doesn't have to overwrite the data until it needs to.
delete doesn't actually delete memory. The memory still exists, your program just doesn't have it allocated anymore, which means it is free to be allocated elsewhere.


It's like the hotel room analogy:

When you check into a hotel room (new), you are given a key (a pointer).
When you check out (delete), you can still keep the key/pointer if you want.

And you can even try to visit the room later. And in fact, the room might be just as you left it. Or someone else might be in there. Or it might have been turned into a janitor's closet.
Yes that is the analogy I was referring to
Registered users can post here. Sign in or register to post.