2012-11-28 27 views
0

我该如何确定一个对象正在使用的内存总量,以及该内存当前存在的内存百分比?那堆呢?
例如,给定此程序:报告对象正在使用堆栈/堆上有多少内存? (GDB)

#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做到这一点吗?
本手册提供了有关examining memory的一些信息,但我无法报告此类信息。

+1

'的sizeof vec'将堆栈大小,因为你分配它的花费叠加。免费的商店大小应该是'vec.capacity()* sizeof(std :: string)''。 – chris

+0

为了测量堆的使用情况,你可以看一下valgrind的地块工具:http://valgrind.org/docs/manual/ms-manual.html –

+1

关于堆,你可能想看看这个gdb扩展:https:/ /fedorahosted.org/gdb-heap/ –

回答

1

如果你准备用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; 
}