Skip to content

Instantly share code, notes, and snippets.

@tarekbadrshalaan
Created March 14, 2020 09:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tarekbadrshalaan/1e9ed2fc927d3a1d9b803579cd461eb1 to your computer and use it in GitHub Desktop.
Save tarekbadrshalaan/1e9ed2fc927d3a1d9b803579cd461eb1 to your computer and use it in GitHub Desktop.
how to use valgrind

REF.Stack-Overflow

C code main.c

#include <stdlib.h>

int main() {
    char* string = malloc(5 * sizeof(char)); //LEAK: not freed!
    return 0;
}

build C code

gcc -o executable -std=c11 -Wall main.c

install valgrind

sudo apt install valgrind  # Ubuntu, Debian, etc.
sudo yum install valgrind  # RHEL, CentOS, Fedora, etc.

run valgrind

valgrind --leak-check=full \
         --show-leak-kinds=all \
         --track-origins=yes \
         --verbose \
         --log-file=valgrind-out.txt \
         ./executable exampleParam1

or

valgrind ./executable

Expected Result

==8082== Memcheck, a memory error detector
==8082== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==8082== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==8082== Command: ./executable
==8082== 
==8082== 
==8082== HEAP SUMMARY:
==8082==     in use at exit: 5 bytes in 1 blocks
==8082==   total heap usage: 1 allocs, 0 frees, 5 bytes allocated
==8082== 
==8082== LEAK SUMMARY:
==8082==    definitely lost: 5 bytes in 1 blocks
==8082==    indirectly lost: 0 bytes in 0 blocks
==8082==      possibly lost: 0 bytes in 0 blocks
==8082==    still reachable: 0 bytes in 0 blocks
==8082==         suppressed: 0 bytes in 0 blocks
==8082== Rerun with --leak-check=full to see details of leaked memory
==8082== 
==8082== For counts of detected and suppressed errors, rerun with: -v
==8082== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment