I'm learning heap and I am told if we have to reassign a pointer to a new address, we have to delete the content in the address of the heap that the pointer points to, or that content becomes garbage and may cause memory leak. Like:
int* x = new int(10);
//delete x
x = new int(12) //without deleting x, the address that holds value 10 becomes garbage.
Therefore I'm thinking although the language doesn't have a GC, why the language is not updated with making a non-pointed heap address be able to be reallocated itself? So when the address is reallocated, the garbage content can be replaced with a new valid value, and therefore garbage collector can be omitted as well?
Thanks, and please point out if I'm wrong :)
There would be no way to implement this without some kind of reference-tracking.
Consider the following modification of your code:
int* y;
// somewhere else:
int* x = new int(10);
y = x;
x = new int(12); // oops: y has now unexpected become invalid
In other words, the memory location pointed to by x
has been copied to another pointer, y
, and then x
has been reassigned. If the reassignment of x
automatically destroyed the data that it previously pointed to, then y
would also become invalid.
That would be undesirable behavior, so you'd need some kind of reference tracking system to ensure that the data pointed to by x
was not deleted unless x
was the only reference to that data.
And now you've just reinvented (a type of) garbage collection.
In fact, though, C++ does have an elegant way of achieving this type of reference tracking: via RAII, or what I prefer to refer to as "scope-bound resource management". Specifically for pointers to memory locations, you would use a smart pointer class to automatically manage the allocation and deallocation of memory as necessary.