Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading