Search code examples
c++pointersmemorydynamicallocation

No error when using pointer after deleting the dynamically allocated memory it points at


I'm learning about dynamic memory in C++. My question is why after removing the variable in the following code I don't get an error?

float* uf = new float(4.26);
delete uf;
cout << uf << '\n';
cout << *uf << '\n';

Solution

  • You mean because it compiles even though it's clearly wrong?

    Arguably, in this case the compiler could produce a warning if it really wanted to, but then it's a simplified, unrealistic situation.

    Consider the following example:

    float* uf = new float(4.26);
    delete uf;
    if (random_condition_known_only_at_runtime()) {
        uf = new float(0.0);
    }
    cout << uf << '\n';
    cout << *uf << '\n';
    

    Or:

    float* uf = new float(4.26);
    if (user_input == 'x') {
        delete uf;
    }
    cout << uf << '\n';
    cout << *uf << '\n';
    

    Or consider concurrency; multiple threads may write to the same pointer.

    The point is that real code will typically depend (directly or indirectly) a lot on I/O operations or other external state like this, making it impossible to know in advance, at compile time, whether the memory pointed to will have been deleted already.


    Or do you mean because the program doesn't crash? That's because the C++ standard does not prescribe crashes. It instead refers to "undefined behaviour", which means that anything can happen, including random crashes or no effect at all. Trying to access memory which was already deleted is a classical example of such undefined behaviour.