How to doing memory debugging and profiling in C with Valgrind


When we playing with C, memory debugging and profiling is a basic need to “break” and doing “analysis” to our C program. Valgrind is a good tools to help us doing memory debugging and profiling. In this case, I use Ubuntu 12.04.

First, we need to install Valgrind by :

1
sudo apt-get install valgrind

Next, let me create some a basic example, format-input.c :

1
2
3
4
5
6
7
8
9
10
#include <stdio.h>

int main(int argc, char *argv[]) {
    int apartment = 3;
    int storey;

    printf("My Apartment number is n");
    printf("My Apartment storey is %dn", storey);
    return 0;
}

In this code, you will see that apartment variable is unused and storey doesn’t have any value. When you doing :

1
2
make format-input
./format-input

You will see result :

1
2
My Apartment number is
My Apartment storey is 0

Definitely we see there two mistaken here but C compiler showing a good result. Well, we can doing deep analysis using Valgrind by :

1
valgrind ./format-input

And you will see the result :

The bottom line here is whatever you’re running your C program, better check with Valgrind to see if everything is goes right 🙂

Fixing the source :

1
2
3
4
5
6
7
8
9
10
#include <stdio.h>

int main(int argc, char *argv[]) {
    int apartment = 3;
    int storey = 33;

    printf("My Apartment number is %dn", apartment);
    printf("My Apartment storey is %dn", storey);
    return 0;
}

And Valgrind result are :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
==8443== Memcheck, a memory error detector
==8443== Copyright (C) 2002-2011, and GNU GPL’d, by Julian Seward et al.
==8443== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info
==8443== Command: ./formating-input
==8443==
My Apartment number is 3
My Apartment storey is 33
==8443==
==8443== HEAP SUMMARY:
==8443==     in use at exit: 0 bytes in 0 blocks
==8443==   total heap usage: 0 allocs, 0 frees, 0 bytes allocated
==8443==
==8443== All heap blocks were freed — no leaks are possible
==8443==
==8443== For counts of detected and suppressed errors, rerun with: -v
==8443== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.