簡體   English   中英

如何獲取所有已分配堆的大小 memory

[英]How to get size of all allocated heap memory

我想知道軟件使用 new/malloc 分配了多少 memory。 我真的不想要堆的大小,因為分配器很可能使用的比我實際分配的要多。 但是我需要這個來檢查代碼的某一部分分配了多少 memory,因此我需要所有新的和 malloc 大小的准確總和。 除了重載 new & malloc 之外,還有什么方法可以做到這一點?

我剛剛開始使用 Linux kernel 編程。 我認為調試堆占用的總 memory 可能有助於調試 memory 在程序的各個部分中使用的趨勢。 我知道,有很多有用/強大的工具(例如 valgrind)可以完成這項工作。 但這可能會花費比必要更多的時間。 為了快速掌握,我認為可以使用“&end”全局字符變量(標識堆開始的位置)和“sbrk(0)”,它報告“程序中斷”地址,例如:

#include <iostream>
#include <unistd.h>
extern char end;
int main(int argc, char* argv[])
{
    std::cout << "heap start: " << (void*)&end << '\n';
    const int RANDSIZE{20};
    void* allocatedPool[RANDSIZE];
    for (int i{0}; i<RANDSIZE; ++i)
    {
         std::cout << "current heap end: " << sbrk(0) << '\n';
         allocatedPool[i] = malloc( RANDSIZE * 4096 );
    }
}

注意:由於開銷/計算優化,看起來 malloc 調用分配的 memory 比頁面多得多 https://unix.stackexchange.com/questions/697960/why-malloc-allocates-more-memory-than-neeed 因此,我使用“20”作為乘數來克服分配的“程序結束”。另外,unistd.h header 文件在內部分配堆,因此它不會匹配“(void*)&end”地址。

程序 output:

current heap end: 0x55f4e3ce1000
current heap end: 0x55f4e3d07000
current heap end: 0x55f4e3d07000
current heap end: 0x55f4e3d2f000
current heap end: 0x55f4e3d2f000
current heap end: 0x55f4e3d57000
current heap end: 0x55f4e3d57000
current heap end: 0x55f4e3d7f000
current heap end: 0x55f4e3d7f000
current heap end: 0x55f4e3da7000
current heap end: 0x55f4e3da7000
current heap end: 0x55f4e3dcf000
current heap end: 0x55f4e3dcf000
current heap end: 0x55f4e3df7000
current heap end: 0x55f4e3df7000
current heap end: 0x55f4e3e1f000
current heap end: 0x55f4e3e1f000
current heap end: 0x55f4e3e47000
current heap end: 0x55f4e3e47000
current heap end: 0x55f4e3e6f000

暫無
暫無

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

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