在我的專案中,我使用一個類進行分頁記憶體分配。這個類使用一個結構來存盤它的所有分配:
enum PageStatus : uint_fast8_t { //!< possible use stati of an allocated page
PAGE_STATUS_INVALID = 0b00,
PAGE_STATUS_FREE = 0b01, //!< the page is free
PAGE_STATUS_USED = 0b10, //!< the page is (partially) used
};
struct PhysicalPage { //!< represents a page that has been allocated
char* pData; //!< pointer to the allocation
PageStatus status; //!< status of the allocation
};
這些PhysicalPages 存盤在一個向量中std::vector<PhysicalPage> physicalAllocations {};。在運行時頁面被添加到向量中,有些可能會被洗掉。在洗掉程序中,最后一個元素被彈出并使用 回傳記憶體delete page.pData。然而,當分配器類到達生命周期結束并從堆疊中釋放時會出現問題。當pyhsicalAllocations的向量解構式被呼叫時,它不僅試圖破壞元素本身,還試圖破壞保留的記憶體(當大小改變時,向量保留作為緩沖區)。這會導致無效的記憶體指標被洗掉,停止程式執行:
double free or corruption (!prev)
Signal: SIGABRT (Aborted)
可能還值得一提的是,分配是在比頁大的塊中完成的,這意味著每個 x 指標中只有一個實際上是有效的分配。所有其他指標都只是從實際記憶體位置的偏移量。
為了防止發生錯誤,我嘗試了:
手動洗掉(由于分塊分配,這有點過于復雜)
for (size_t i = physicalAllocations.size(); 0 < i; i -= 1 << allocationChunkSize) {
delete physicalAllocations[i - (1 << allocationChunkSize)].pData;
for (size_t a = 0; a < 1 << allocationChunkSize; a )
physicalAllocations.pop_back();
}
清除向量
physicalAllocations.clear();
交換一個清晰的向量
std::vector<PhysicalPage>(0).swap(physicalAllocations);
其中沒有一個作業。
我已經在這個問題上作業了很長時間,我想承認,非常感謝您的幫助。謝謝!
uj5u.com熱心網友回復:
std::shared_ptr<char[]> pData它的別名建構式 (8)可能會有所幫助。(這甚至可能允許擺脫 PageStatus)。
它看起來像:
constexpr std::size_t page_size = 6;
struct PhysicalPage {
std::shared_ptr<char[]> pData;
};
int main()
{
std::vector<PhysicalPage> pages;
{
std::shared_ptr<char[]> big_alloc = std::unique_ptr<char[]>(new char[42]{"hello world. 4 8 15 16 23 42"});
for (std::size_t i = 0; i != 42 / page_size; i) {
pages.push_back(PhysicalPage{std::shared_ptr<char[]>{big_alloc, big_alloc.get() i * page_size}});
}
}
pages.erase(pages.begin());
pages.erase(pages.begin() 2);
for (auto& p : pages) {
std::cout << std::string_view(p.pData.get(), page_size) << std::endl;
}
}
演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/370435.html
下一篇:本地與全域宣告
