A popular framework for memory profiling is Valgrind (available from the Ubuntu main
repository). In particular, you could use its massif heap profiling tool. For example, given a minimal C program:
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
int main(void)
{
void *p;
if ( (p = malloc( (size_t)1024*1024 )) == NULL) {
fprintf(stderr, "memory allocation failure");
exit(ENOMEM);
}
free(p);
return EXIT_SUCCESS;
}
compiled with gcc -Wall -o myprog myprog.c
, then
$ valgrind --tool=massif ./myprog
==5145== Massif, a heap profiler
==5145== Copyright (C) 2003-2017, and GNU GPL'd, by Nicholas Nethercote
==5145== Using Valgrind-3.18.1 and LibVEX; rerun with -h for copyright info
==5145== Command: ./myprog
==5145==
==5145==
You can read the output directly from the default massif.out.<pid>
file, or pretty-print it with ms_print
:
$ ms_print massif.out.5145
---------------------------------------------
Command: ./myprog
Massif arguments: (none)
ms_print arguments: massif.out.5145
---------------------------------------------
MB
1.000^ #
| #
| #
| #
| #
| #
| #
| #
| #
| #
| #
| #
| #
| #
| #
| #
| #
| #
| #
| #
0 +--------------------------------------------->ki
0 159.8
Number of snapshots: 4
Detailed snapshots: [2 (peak)]
---------------------------------------------
n time(i) total(B) useful-heap(B) extra-heap(B) stacks(B)
---------------------------------------------
0 0 0 0 0 0
1 163,567 1,048,584 1,048,576 8 0
2 163,607 1,048,584 1,048,576 8 0
100.00% (1,048,576B) (heap allocation functions) malloc/new/new[], --alloc-fns, etc.
->100.00% (1,048,576B) 0x1091BE: main (in /home/steeldriver/src/myprog)
---------------------------------------------
n time(i) total(B) useful-heap(B) extra-heap(B) stacks(B)
---------------------------------------------
3 163,607 0 0 0 0