Allocating memory using new returns same memory address

后端 未结 5 869
清酒与你
清酒与你 2021-01-21 08:38
class abc  {
    int x ;
};
int main()
{
    abc *A = new abc ;
    cout<< static_cast(A) << endl ;
    delete A ;
    cout<< static_cast&         


        
5条回答
  •  不要未来只要你来
    2021-01-21 09:15

    Why should this not happen? Once you've deleted memory at a particular address, the memory manager is perfectly at liberty to re-use that address the next time you ask for new memory. Indeed this is a very common optimisation used by memory managers. They keep track of recently freed blocks and hand them back to the next client that requests a block of that size.

    Another way to look at this would be to consider what would happen if freed addresses were never re-used. If that were to happen then eventually, after enough allocation/deallocation cycles, there would be no address space left. Indeed, if re-use never happened then there would be no point at all in deallocating memory. So yes, do expect that when you deallocate memory, that memory address will be re-used.

提交回复
热议问题