What happens to an address after delete operator has been applied to it in C++?

前端 未结 5 608
春和景丽
春和景丽 2020-12-19 09:51

If I delete a pointer as follows for example:

delete myPointer;

And, after that did not assign 0

5条回答
  •  清酒与你
    2020-12-19 10:24

    This question is important! I have seen that Visual Studio 2017 has changed pointer value after "delete". It coused a problem because I has using memory tracing tool. The tool was collecting pointers after each operator "new" and was checking them after "delete". Pseudo code:

    Data* New(const size_t count)
    {
        Data* const ptr(new Data[count]);
        #ifdef TEST_MODE
        MemoryDebug.CollectPointer(ptr);
        #endif
        return ptr;
    }
    
    void Delete(Data* const ptr)
    {
        delete[] ptr;
        #ifdef TEST_MODE
        MemoryDebug.CheckPointer(ptr);
        #endif
    }
    

    This code works good on Visual Studio 2008 but was failing on Visual Studio 2017 so I have changed the order of operations in second function.

    However the question is good and the problem exists. Experienced engineers should be aware of that.

提交回复
热议问题