[Linux] Debug your own programs [GDB/Valgrind]

Installation:

  • GDB

GDB is normally included in your Linux distribution. Otherwise:

Download the latest version of GDB (ending with .tar.gz), here. Then, follow this guide to install it.

  • Valgrind

Nothing easier than this:

sudo apt-get install -y valgrind

N.B.: You’ll need roughly 130MB of free space.

Basic functions:

  • GDB

For launching GDB on a program, do not forget to compile it with -g just after your compiler (ex.: gcc -g […]) and then:

gdb ./my_prog

You then have to put break points where you want GDB to stop the program execution and give you the hand on it:

break my_function /*or b my_function; N.B.: main is a function !*/
/*For stopping in the middle of a function:*/
b my_file.c:line_number /*ex.: b test_segfault.c:8*/

Then make it run your program until it reaches a break point:

run /*or r*/

If ever your program is expecting arguments, you can link your program to arguments while running in GDB with:

r argument1 argument2 argument3 ... argumentn

When GDB reaches a break point, it is waiting for a user entry which can be:

step /*or s; to step in the first function found in the line*/
next /*or n; to execute the line where the debugger stopped the program*/
continue /*or c; to continue to the next reached break point*/
next x /*or n x; to execute n line before stopping (useful for jumping long loops)*/
print variable1 variable2 variable3 pointer1 *valueofpointer /*or p variable1 [...]*/

You can exit GDB with:

quit /*ou q*/
  • Valgrind

To launch Valgrind (add the -g after the compiler for compiling otherwise it would not let you know where errors are situated):

valgrind ./my_prog

And if your program is expecting arguments:

valgrind ./mon_prog argument1 argument2 argument3 ... argumentn
Publicités

Laisser un commentaire

Entrez vos coordonnées ci-dessous ou cliquez sur une icône pour vous connecter:

Logo WordPress.com

Vous commentez à l'aide de votre compte WordPress.com. Déconnexion / Changer )

Image Twitter

Vous commentez à l'aide de votre compte Twitter. Déconnexion / Changer )

Photo Facebook

Vous commentez à l'aide de votre compte Facebook. Déconnexion / Changer )

Photo Google+

Vous commentez à l'aide de votre compte Google+. Déconnexion / Changer )

Connexion à %s