c++ - Allocating memory using new returns same memory address -
class abc { int x ; }; int main() { abc *a = new abc ; cout<< static_cast<void*>(a) << endl ; delete ; cout<< static_cast<void*>(a) << endl ; abc *b = new abc ; cout<< static_cast<void*>(b) << endl ; delete b ; cout<< static_cast<void*>(b) << endl ; return 0; }
why prints same address , though deleted old memory .
assign null after deletion , prints same address.
even address of , b same .
real time scenario :
function1 -> arr[p] = new x ptr1 = arr[p] using ptr1 function2 -> ptr2 = arr[p] delete ptr2 arr[p] = new x ( new data)
in real scenario ptr1 should invalidated since compiler assign same address to
arr[p] in function2 ptr1 still works .
why should not happen? once you've deleted memory @ particular address, memory manager @ liberty re-use address next time ask new memory. indeed common optimisation used memory managers. keep track of freed blocks , hand them next client requests block of size.
another way @ consider happen if freed addresses never re-used. if happen eventually, after enough allocation/deallocation cycles, there no address space left. indeed, if re-use never happened there no point @ in deallocating memory. yes, expect when deallocate memory, memory address re-used.
Comments
Post a Comment