int main(){
char *Allocation;
Allocation = new char[8]; //here is out first allocation;
delete[] Allocation; //after while we delete it;
Allocation = new char[16];//then we allocate some chunk of memory again to our pointer;
delete[] Allocation; //then finally we delete our second allocation;
}
Is this valid in C++? Does the first allocation affect the second allocation? Can I allocate a new memory block to a deleted pointer?
tl;dr Yes, that's perfectly fine.
You have to distinguish between the actual value in memory and the value of the pointer variable that points to this actual value in memory.
newprovides the actual value in memory (which is not bound to a variable) and returns its address. This returned address is then set by assignment as the value of the variableAllocation.With
deleteyou remove the actual value from memory. But this usually does not affect the value of the variableAllocation. The address is therefore retained, but must no longer be dereferenced. It is undefined what happens if you do this anyway.Therefore it is recommended to assign a
nullptr(null pointer) toAllocationright after callingdelete. Some implementations do assign anullptrimplicitly afterdeleteif the program is compiled in debug mode. Therefore the usually above.A
nullptris just the address with the value0. An access on this address is always invalid, so its the common value to imply that a pointer doesn't point to a valid location.So you can assign a different address as value to the variable
Allocationat any time. The memory managed withnewanddeleteexists independent of variables. These are only used for access.By the way, you should initialize your variable
Allocationwith either a call tonewor with anullptr. Otherwise your variableAllocationmay contain some random valueLive code at Compiler Explorer
Output:
Note that C++ distinguishes between initialization and assignment: