Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Total glibc malloc() bytes

How do I get the total number of bytes malloc()'d in a program (Assume I am running with glibc)? I do not want to see how much memory the program is taking, I want to see how much memory I allocated. Below is an example program where these numbers would be very different.

#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

using namespace std;

int main() {
    vector<void *> p;
    printf("Allocating...\n");
    for (size_t i = 0; i < 1024 * 1024 * 10; ++i) {
        p.push_back(malloc(1024));
        memset(*p.rbegin(), 0, 1024);
    }
    printf("Press return to continue...\n");
    getchar();
    printf("Freeing all but last...\n");
    for (size_t i = 0; i < p.size() - 1; ++i)
        free(p[i]);
    printf("Press return to continue...\n");
    getchar();

    // UNTIL THIS FREE, TOP WOULD SHOW THIS PROGRAM TAKES 16G,
    // BUT THE TOTAL MALLOC() SIZE IS MUCH LESS.

    printf("Freeing last...\n");
    free(*p.rbegin()); 
    printf("Press return to continue...\n");
    getchar();
}

I know this can be implemented with LD_PRELOAD or by having my own malloc and free functions, but is there a simpler way to get the malloc() total?

like image 545
tohava Avatar asked Aug 04 '26 23:08

tohava


2 Answers

The various language standards say:

There is no platform independent way of getting this information. Different implementations of malloc may provide this information, but it would be in a non-standard way.

Glibc offers:

  • You could use the __malloc_hook feature to write up a hook that counts how much memory has been allocated.

  • There's also mallinfo(), which should provide some information about what memory has been allocated.

like image 111
Bill Lynch Avatar answered Aug 06 '26 12:08

Bill Lynch


Make a global variable and your own malloc() function

static size_t count;

void *malloc_ex(size_t n)
{
    count+=n;
    return malloc(n);
}

Then any time you can now how many bytes were allocated by looking inside the countvariable.

Global variables are initialized to 0 by the compiler so it will be ok. And please do not #undef malloc and re #define it as malloc_ex() this will be Undefined Behavior.

like image 40
Valentin Mercier Avatar answered Aug 06 '26 13:08

Valentin Mercier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!