One of the main reason of segmentation fault error is incorrect memory management, e.g freeing unallocated or static space, unauthorized access to unavailable memory. Unfortunately, it isn’t possible to figure out why our application doesn’t work after the segmentation fault message, without any additional tool.
Memory leeks are another problem, which refer to programs written in C/C++. It is especially important in case of embedded systems which are designed to permanently do specific tasks. Embedded C/C++ developers have to provide efficient solution for resource (e.g memory) management.
A tool which will help us to get rid of memory management problems is Valgrind. It consists of several modules:
Before we use Valgrind – any of its module – our code have to be compiled with gcc or g++ compiler with “-g” flag and without any optimizations (-o0). It is worth to define separate compilation modes for debug (with above flags) and release (without them) versions of our application.
Memcheck it is a part of Valgrind which checks if we correctly use memory e.g if we have memory leeks or not. To run Memcheck, we need to use command as below.
valgrind --leak-check=full my_program
As a result, we get an important information about places where memory leeks occur.
Cachegrind/Callgrind might be used to find places where our program slows and optimize them. It counts, how many times each line of our code was called. Information about that is stored in a single report.
valgrind --tool=cachegrind my_program valgrind --tool=callgrind my_program
Massif is a module which calculates memory usage during the time a program is running. Furthermore, it marks places in our code, which have the greatest impact on such memory usage. Massif especially helps during the implementation of embedded systems, web-services. Such applications require optimal resource management rules.
valgrind --tool=massif my_program
Hellgrind is a tool which checks the synchronization in multi-threaded applications. Hellgrind is able to mark the line from our code which caused the segmentation fault error.
valgrind --tool=helgrind my_program
Valgrind and all described modules can be integrated with Eclipse IDE. To do that, we need to install standalone Valgrind and a plugin from Linux Tools packet. After that, we get an access to a very convenient graphic user interface, connected with Valgrind engine. We will be able to switch between errors, detected with Valgrind and corresponding lines of our code.
Valgrind supports many platforms e.g Unix, ARM, but it doesn’t support the Microsoft Windows. It isn’t also possible to install Valgrind plugin for Eclipse IDE on Windows platform.