c++pointersmemorycastingaccess-violation

Memory issues when converting a pointer to std::uint64_t and back to a pointer again


The code is shown below.

struct tNode
{
    int data;
    tNode* next;
    tNode(const int& data, tNode* next = nullptr)
    {
        this->data = data;
        this->next = next;
    }
};

int main()
{
    tNode* ptr = new tNode(1);
    std::uint64_t num_ptr = reinterpret_cast<std::uint64_t>(ptr);
    delete ptr;
    auto back_to_ptr = reinterpret_cast<tNode*>(num_ptr);
    tNode* ret = back_to_ptr->next;
    std::cout << ret;
}

When I tried debugging in Visual Studio 2022 using the MSVC compiler, I could not detect any errors. I believe tNode* ret = back_to_ptr->next; should output error information about a memory access violation, so why is the above code working fine?

I've been searching for problems with converting pointers to int types. Using Visual Studio 2022, I debugged the above example by taking breakpoints.


Solution

  • The issue here, fortunately, has nothing to do with the casting from integers to pointers or vice versa. Rather, the issue is that the line delete ptr does not do anything to ptr itself but instead destroys the object it points at. Any further use of that object, regardless of how you get a pointer to it, is classified as undefined behavior. That means that you might get a memory error, or you might not. In your case, it just so happens that you don’t get a crash or access violation even though what you’re doing clearly accesses an object after its lifetime ends.