Trevor Hickey
Trevor Hickey

Reputation: 37914

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

How would I determine the total amount of memory an object is using, and what percentage of that memory currently exists on the stack? What about the heap as well?
For example, given this program:

#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;
}

how can I view the size of the stack and heap before and after the creation of the vector?
Is this possible to do this with GDB?
The manual provides some information on examining memory, but I haven't been able to report such information.

Upvotes: 0

Views: 1914

Answers (1)

If you're prepared to use GLIBC specific functions you can use mallinfo() directly within your program to answer the question:

#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;
}

Upvotes: 2

Related Questions