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