Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save felipeek/f9e4392cfe9a9e65dc52048e91ac58ea to your computer and use it in GitHub Desktop.
Save felipeek/f9e4392cfe9a9e65dc52048e91ac58ea to your computer and use it in GitHub Desktop.
Analyze memory usage with valgrind and massif

Approach 1: run a process with massif, let it take automatic memory snapshots and then analyze the results

Approach 2: run a process with massif, manually decide when the snapshots are taken, and then analyze the results

Approach 1

    1. Run your process with massif: valgrind --tool=massif <your executable> <your process arguments>
    1. Do whatever you need to do, and then stop your process. A file named ms_print massif.out.pid will be generated.
  • 3a. Option 1: Run ms_print massif.out.*pid* > user_friendly.txt to generate a user-friendly file and analyze it.
  • 3b. Option 2: Run massif-visualizer massif.out.*pid* to visualize the results in a pretty UI. You need to install massif-visualizer: sudo apt install massif-visualizer

Approach 2

    1. Run your process with massif: valgrind --tool=massif --vgdb=yes --vgdb-error=0 <your executable> <your process arguments>
    1. In another shell, run gdb <your process>. The next commands will be all related to this new shell.
    1. Run target remote | /usr/bin/vgdb (NOTE: change /usr/bin/vgdb to your vgdb installation, if necessary. You can run which vgdb to confirm)
    1. Run break your_file.c:LINE to put a breakpoint, e.g. break my_file.c:193. Put breakpoints in all places needed since you will only be able to generate snapshots once a breakpoint is hit.
    1. Run continue or simply c to continue execution.
    1. Once a breakpoint hits, type monitor detailed_snapshot <filename> to generate a snapshot. Do this for each snapshot you wanna generate. Always use different filenames.
    1. Once you generate your last snapshot, type monitor all_snapshots <all_snapshots_filename> to generate a final result, merging all previously-generated snapshots. You just need to specify the name of the final file, all files that were generated previously are automatically tracked.
  • 8a. Option 1: Run ms_print <all_snapshots_filename> > user_friendly.txt to generate a user-friendly file and analyze it.
  • 8b. Option 2: Run massif-visualizer <all_snapshots_filename> to visualize the results in a pretty UI. You need to install massif-visualizer: sudo apt install massif-visualizer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment