报告对象正在使用堆栈/堆上的内存量?(GDB)

Report how much memory on stack/heap is being used by an object? (GDB)

本文关键字:内存 GDB 对象 堆栈 报告      更新时间:2023-10-16

如何确定对象正在使用的内存总量,以及堆栈上当前存在的内存百分比是多少?那堆呢?
例如,给定此程序:

#include <cstdlib>
#include <vector>
#include <string>
int main(){
    //I wonder how much memory is being 
    //used on the stack/heap right now.
    std::vector<std::string> vec{"11","22","33"};
    //how about now?
    return EXIT_SUCCESS;
}

如何查看创建向量前后的堆栈和堆的大小?
这可以用GDB做到这一点吗?
该手册提供了一些关于检查记忆的信息,但我无法报告这些信息。

如果您准备使用 GLIBC 特定函数,则可以直接在程序中使用 mallinfo() 来回答以下问题:

#include <cstdlib>
#include <vector>
#include <string>
#include <iostream>
#include <malloc.h>
int main(){
    std::cout << "Using: " << mallinfo().uordblks << "n";
    std::vector<std::string> vec{"11","22","33"};
    std::cout << "Using: " << mallinfo().uordblks << "n";
    return EXIT_SUCCESS;
}