使用new分配内存返回相同的内存地址
class abc {
int x ;
};
int main()
{
abc *A = new abc ;
cout<< static_cast<void*>(A) << endl ;
delete A ;
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;
}
即使我删除了旧内存,为什么它仍打印相同的地址.
即使我在删除后指定null,它也会打印相同的地址.
Why it prints the same address , even though i deleted old memory .
Even i assign null after deletion , it prints the same address.
A和B的地址都相同.
Even address of A and B is same .
实时场景:
Function1 ->
arr[p] = new X
ptr1 = arr[p]
using ptr1
Function2 ->
ptr2 = arr[p]
delete ptr2
arr[p] = new X ( new data)
在实际情况下,应该使ptr1无效,但是由于编译器将相同的地址分配给
function2 ptr1中的arr [p]仍然有效.
In real scenario ptr1 should be invalidated but since compiler assign same address to
arr[p] in function2 ptr1 still works .
为什么不应该这样呢?一旦删除了特定地址的内存,内存管理器便可以自由地在下次请求新内存时重用该地址.确实,这是内存管理器使用的非常常见的优化.他们会跟踪最近释放的块,并将其交给要求该大小的块的下一个客户端.
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.