Difference between revisions of "Valgrind"

From Linuxintro
imported>ThorstenStaerk
(New page: With valgrind you can analyze your program's memory behavior.)
 
imported>ThorstenStaerk
 
Line 1: Line 1:
 
With valgrind you can analyze your program's memory behavior.
 
With valgrind you can analyze your program's memory behavior.
 +
 +
Example:
 +
 +
You write a short program that has a memory leak:
 +
<pre>
 +
#include <iostream>
 +
using namespace std;
 +
 +
void pollute()
 +
{
 +
  int* i=new int();
 +
  cout << i << "  ";
 +
}
 +
 +
int main()
 +
{
 +
  { pollute(); }
 +
}
 +
</pre>
 +
Compile it
 +
g++ main.cpp
 +
and valgrind it:
 +
<pre>
 +
valgrind ./a.out
 +
==21506== Memcheck, a memory error detector
 +
==21506== Copyright (C) 2002-2010, and GNU GPL'd, by Julian Seward et al.
 +
==21506== Using Valgrind-3.6.1 and LibVEX; rerun with -h for copyright info
 +
==21506== Command: ./a.out
 +
==21506==
 +
0x5936040  ==21506==
 +
==21506== HEAP SUMMARY:
 +
==21506==    in use at exit: 4 bytes in 1 blocks
 +
==21506==  total heap usage: 1 allocs, 0 frees, 4 bytes allocated
 +
==21506==
 +
==21506== LEAK SUMMARY:
 +
==21506==    definitely lost: 4 bytes in 1 blocks
 +
==21506==    indirectly lost: 0 bytes in 0 blocks
 +
==21506==      possibly lost: 0 bytes in 0 blocks
 +
==21506==    still reachable: 0 bytes in 0 blocks
 +
==21506==        suppressed: 0 bytes in 0 blocks
 +
==21506== Rerun with --leak-check=full to see details of leaked memory
 +
==21506==
 +
==21506== For counts of detected and suppressed errors, rerun with: -v
 +
==21506== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 6 from 6)
 +
</pre>

Latest revision as of 10:44, 19 May 2012

With valgrind you can analyze your program's memory behavior.

Example:

You write a short program that has a memory leak:

#include <iostream>
using namespace std;

void pollute()
{
  int* i=new int();
  cout << i << "  ";
}

int main()
{
  { pollute(); }
}

Compile it

g++ main.cpp

and valgrind it:

 valgrind ./a.out 
==21506== Memcheck, a memory error detector
==21506== Copyright (C) 2002-2010, and GNU GPL'd, by Julian Seward et al.
==21506== Using Valgrind-3.6.1 and LibVEX; rerun with -h for copyright info
==21506== Command: ./a.out
==21506== 
0x5936040  ==21506== 
==21506== HEAP SUMMARY:
==21506==     in use at exit: 4 bytes in 1 blocks
==21506==   total heap usage: 1 allocs, 0 frees, 4 bytes allocated
==21506== 
==21506== LEAK SUMMARY:
==21506==    definitely lost: 4 bytes in 1 blocks
==21506==    indirectly lost: 0 bytes in 0 blocks
==21506==      possibly lost: 0 bytes in 0 blocks
==21506==    still reachable: 0 bytes in 0 blocks
==21506==         suppressed: 0 bytes in 0 blocks
==21506== Rerun with --leak-check=full to see details of leaked memory
==21506== 
==21506== For counts of detected and suppressed errors, rerun with: -v
==21506== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 6 from 6)