Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make valgrind report an error when there are still reachable allocs

I'm writing a compiler that produces C code. The programs produced consist only of the main function, and they use a lot of memory, that is allocated with malloc(). Most of the memory allocated is used only in a small part of the program, and I thought it would be a good idea to free() it after use, since it's not going to be used again. I would be glad, then, if valgrind would report to me about memory not free()d in the end of the program, that is, still reachable memory. I'm using valgrind with --error-exitcode=1 inside a Makefile, to check for this kind of problem automatically.

The question is: is there a way to make valgrind exit with 1 in case there are still reachable allocs?

like image 437
marcot Avatar asked May 20 '11 11:05

marcot


3 Answers

An alternative to grepping through Valgrind output: modify your compiler so it emits:

int main() { return foo_main(); }
int foo_main() {  /* whatever you've emitted before */ }

Assuming you are not assigning allocated blocks to global variables (which would make no sense since you only have one function), you've just transformed "still reachable" into "definitely leaked".

Possibly even better transformation: don't call exit(0) in your main; change it to return 0; instead. The net effect should be same as above -- __libc_main will now call exit for you, and all local variables in main will be out of scope by that time.

like image 89
Employed Russian Avatar answered Sep 27 '22 21:09

Employed Russian


The valgrind manual says:

Indirectly lost and still reachable blocks are not counted as true "errors", even if --show-reachable=yes is specified and they are printed; this is because such blocks don't need direct fixing by the programmer.

I have found no way to make valgrind report "still reachable"s as error. It seems to be that your only option to do this (other than patching valgrind) is to capture the output of valgrind and parse the "still reachable" line.

like image 42
Lesmana Avatar answered Sep 27 '22 22:09

Lesmana


The poroper options to use to exit with error when there is a reachable block at exit:

valgrind --tool=memcheck --leak-check=full --show-reachable=yes --errors-for-leak-kinds=all

From Valgrind manual:

Because there are different kinds of leaks with different severities, an interesting question is: which leaks should be counted as true "errors" and which should not?

The answer to this question affects the numbers printed in the ERROR SUMMARY line, and also the effect of the --error-exitcode option. First, a leak is only counted as a true "error" if --leak-check=full is specified. Then, the option --errors-for-leak-kinds= controls the set of leak kinds to consider as errors. The default value is --errors-for-leak-kinds=definite,possible

like image 35
hesham_EE Avatar answered Sep 27 '22 23:09

hesham_EE