c++memory-managementnew-operatordelete-operator

In C++, how does the delete operator actually work? (At the memory level)


I know it free memory from the heap. But how does the program know that the memory being freed (or not freed). If I have to guess, there's some kind of "available-memory-list" somewhere in the program's memory. If that's the case, how does that list structured? Is it managed by the program or by the operating system?

I created a simple program to tryna find out whats going on :

#include <iostream>
int main () {
    int* ptr = new int;

    *ptr = 0xFFFFFFFF;

    std::cout << ptr << std::endl;      //some random 64-bit address
    std::cout << *ptr << std::endl;     //-1

    delete ptr;

    std::cout << ptr << std::endl;      // always 0x0000000000008123
    std::cout << *ptr << std::endl;     // Exception thrown: read access violation.

    return 0;
}

Memory location pointed by ptr before the delete operator:

memory location pointed by ptr

That same memory location but after the delete operator:

That same memory location but after the delete operator

Why is that old memory location always filled with 0xDDDDDDDD after being deleted? Is it a mark that indicates the memory is freed? Why is it even bother doing so if it already keeps track of it in the assuming "available-memory-list"? I mean writing to memory take some effort (even though negligible in this example), why don't just leave it there until something else overwrite on it.

Although initially the ptr is pointing to some random address, but after the delete operation, it always pointing to 0x0000000000008123. Is it also a mark that indicates the pointer is now pointing to an inaccessible memory block?

(I'm using visual studio 2022 on a windows 10, 64-bit operating system)

Just some links to a good article can also be helpful. Thank you.


Solution

  • Why is that old memory location always filled with 0xDDDDDDDD after being deleted?

    Your platform's debug build does a memset on the memory to 0xDD after being freed.

    It is not specified in the standard. It is an implementation detail, specific to your platform.

    q.v. magic number for the DDDDDDDD value.

    Is it a mark that indicates the memory is freed? Why is it even bother doing so if it already keeps track of it in the assuming "available-memory-list"? I mean writing to memory take some effort (even though negligible in this example), why don't just leave it there until something else overwrite on it.

    It is there to aid in debugging.

    Although initially the ptr is pointing to some random address, but after the delete operation, it always pointing to 0x0000000000008123. Is it also a mark that indicates the pointer is now pointing to an inaccessible memory block?

    Probably not. It's undefined behavior even to access ptr after the delete ptr; statement. You should ptr = nullptr; after the delete so it is legal to access the value of ptr again.