0

in this code as you can see used DMA and deleted p but the p[0] is still accessable. how is this possible. or am i missing something

#include<iostream>

using namespace std;
int i = 0;
class T {
    public:
    int id;
    T() {
        i++;
        id = i;
        cout << "Created: " << id << endl;
    }
    ~T() {
        cout << "Deleted: " << id << endl;
    }
};

int main() {
    T *p = new T[10];
    delete p;
    cout << "Id: " << p[0].id; // how it is still accessable
}

output

Created: 1
Created: 2
Created: 3
Created: 4
Created: 5
Created: 6
Created: 7
Created: 8
Created: 9
Created: 10
Deleted: 1
Id: 1
Gaurav Bhardwaj
  • 326
  • 2
  • 8
  • 1
    As soon as you accessed `p[0].id` after doing `delete p`, the behaviour was undefined. Anything can happen from there, including what you are seeing. Undefined behaviour does not mean "program should crash" or "value should be inaccessible". It means that no particular behaviour is guaranteed. – Peter Mar 28 '20 at 06:41
  • 1
    Simple case of *undefined behaviour*. Being `still accessible` is one possible outcome when the bahviour is undefined. So is crashing of course. – john Mar 28 '20 at 06:42
  • 1
    @Peter Strictly, when the behaviour is undefined anything can happen for the entire program, not just from the point when the invalid access occurred. – john Mar 28 '20 at 06:44
  • 1
    Btw. you already have undefined behavior at `delete p` because `p` was allocated for with an array new, in which case `delete[]` *must* be used instead. This also explain why seemingly only one of the objects is deleted in your output. – walnut Mar 28 '20 at 06:48
  • 1
    @john - Can you point to a clause in the standard that says the behaviour of the *whole program* is undefined. While I realise that a compiler is permitted (but not required) to diagnose undefined behaviour, I'm aware of nothing which suggests, for example in this question, that `T *p = new T[10]` has undefined behaviour because the wrong version of operator `delete` is subsequently used, or because `p[0]` is accessed after `delete p`. – Peter Mar 28 '20 at 06:53
  • 1
    @Peter If there is undefined behavior in the execution path for a given input, then there are no guarantees on the program execution, even preceding the undefined operation, see https://eel.is/c++draft/intro#abstract-5. For example the initial `Created:` output would not need to be given because the UB path will always be chosen. – walnut Mar 28 '20 at 06:57
  • 1
    Thanks @walnut. I've learned something. Also found a similar clause in the 1998 standard (albeit worded slightly differently), so it's been true for all C++ standards. – Peter Mar 28 '20 at 08:04

0 Answers0