Allocating memory using new returns same memory address

后端 未结 5 782
清酒与你
清酒与你 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条回答
  • 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.

    0 讨论(0)
  • 2021-01-21 09:15

    it is because you are deleting the pointers.do not delete them you will see the difference.

    abc *A = new abc ;
    abc *B = new abc ;
    
    0 讨论(0)
  • 2021-01-21 09:16
    abc *A = new abc ;
    

    This will allocate enough memory to hold abc object and make A point to that address( Let's say address is 0x1234). So, A contains value 0x1234.

    delete A;

    will deallocate that memory( that means memory is returned to free store). But A still contains the value of that memory address i.e 0x1234.

    Deleting same pointer two times makes for undefined behavior is a conseqeunce of this thing only as second time you would be deleting the memory which is not yours.

    That's why you do

    A= NULL;
    

    after deleting the memory.

    0 讨论(0)
  • 2021-01-21 09:29
    abc *A = new abc ;
    cout<< static_cast<void*>(A) << endl ;
    

    This is the first output.

    delete A ;
    cout<< static_cast<void*>(A) << endl ;
    

    Though it is after delete the value of A remains the same. What delete did was: 1. call the destructor (in this case trivial) of A and 2. Inform the memory allocator that the memory allocated for A is now free and can be used for other purposes.

    abc *B = new abc ;
    cout<< static_cast<void*>(B) << endl ;
    

    It may be that in this step output will be still the same - since allocator has the memory previously allocated for A for use now, it may use it for B.

    delete B ;
    cout<< static_cast<void*>(B) << endl ;
    

    The same as before with A.

    0 讨论(0)
  • 2021-01-21 09:40

    Memory you freed is not used anymore. Memory manager can use the heap as it wants - allocating next free space - the one you actually freed just before.

    0 讨论(0)
提交回复
热议问题