簡體   English   中英

為什么使用 realloc 重新分配,使用 allocator::allocate 預先分配的 memory 保存舊的起始 memory 地址?

[英]Why does reallocating with realloc, a pre-allocated memory using allocator::allocate conserve the old start memory address?

主要問題是重新分配 memory,同時擴展它並保存數據和第一個起始 memory地址,該地址被程序的許多其他部分使用(例如 ZA81259CEF8E959C624ZDF1D456E5D329 起始內存)

這對 realloc 不起作用,因為他解除了分配的先例 memory 並影響另一個具有新的起始 memory 地址:

 using namespace std;

 int *t = static_cast<int*>(malloc( 2*sizeof(int)));
   cout << "address " << t << endl;

 t = static_cast<int*>(realloc(t,10*sizeof(int)));
   cout << "address " << t << endl;

=========================

 // both of the addresses are different
 address 0x55c454fc5180
 address 0x55c454fc55b0

在測試了許多解決方案(甚至通過系統調用直接訪問 memory)后,我發現了這個:

 allocator<int> alloc;
 int *t = alloc.allocate(2*sizeof(int));
   cout << "address " << t << endl;

 // reallocating memory using realloc
 t = static_cast<int*>(realloc(t, 10*sizeof(int)));
   cout << "address " << t << endl;

=========================
 
 // now the addresses are the same 
 address 0x55c454fc5180
 address 0x55c454fc5180

我試圖解釋它是如何可能的,但無法同時滿足這兩種功能,我想知道它為什么以及如何工作。

在使用std::allocator分配的地址上使用reallocnew或類似的東西具有未定義的行為。 它只能在地址來自malloc / calloc / realloc系列分配函數時使用。 切勿混合它們。

一般來說, realloc不保證分配的地址保持不變。 無法保證realloc能夠就地擴展分配(例如,在當前分配之后可能沒有足夠的 memory 空閑)。 在這種情況下,將 memory 塊復制到有足夠可用空間的新分配是realloc的定義行為。 這也意味着realloc只能用於 C++ 中的普通可復制類型。

如果你的程序依賴於分配的地址保持不變,那么它就不能擴展分配。 你可以擁有其中之一,而不是兩者兼而有之。


此外,您使用的std::allocator<int>錯誤。 .allocate的參數應該是要分配的數組元素的數量,而不是字節數。 然后,您應該在數組的每個元素上調用std::allocator_traits<std::allocator<int>>::constructstd::construct_at或放置新來構造和啟動數組元素的生命周期。

我不確定你為什么要在這里使用std::allocator ,但你不太可能需要它。 如果您只是打算創建一個int數組,則應使用new int[n]而不是std::allocator 或者更不用擔心手動 memory 管理,只需使用std::vector<int>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM