I am currently learning about dynamically allocated memory and have written a short program for practise.
Here is the main function:
int main() {
// Local variables are stored in the stack.
// The heap is a pool of unused memory that can be used when the program dynamically allocates memory.
// The `new` operator allocates memory within the heap and returns the address of that variable:
int *p = new int;
*p = 5;
cout << "A variable has just been allocated in the heap" << endl;
cout << "Its memory address is: " << p << endl;
cout << "Its value is: " << *p << endl;
// For local variables on the stack, memory management is performed automatically.
// But on the heap, it must be done manually.
// Memory must be freed when no longer needed:
delete p; // This frees up the memory pointed to by p.
// The `delete` keyword frees up the memory allocated for the variable, but does not delete the pointer p, because p is stored on the stack.
// p is now a dangling pointer, it points to a non-existent memory location.
// To test that it worked:
cout << "The memory previously pointed to has now been deleted." << endl;
cout << "Its memory address is: " << p << endl;
cout << "Its value is: " << *p << endl;
}
So far it makes sense, except for line delete p
. At that point, the memory is supposed to be 'freed up'. I read the following page for information:
Delete in c++ program is not freeing up memory
The answer said:
Calling
delete whatever
marks that memory as deallocated and free for future use.
However, when I run the program, the two sets of cout
statements output the same thing, which to me suggests that the memory has not been freed up, as p
still points to the same location, which has the same value.
After some tinkering, I found that I can reallocate p
whether or not I ran delete p
and I could change the memory address and its value in either case.
So what exactly does delete p
do, I don't notice it making any difference to the program?