209
37
free(stack);
38
return 0;
39 }
In line 36, we are incorrectly assigning the value 1234 to the position 100, which is
outside the array range of 0-99. If we compile and run this code, it may not fail. This is
because, even if we only allocated 400 bytes (100 integers) for our array, the operating
system provides a whole memory page, typically 4KiB. Executing the binary under
Valgrind reports an issue, shown in Listing 12-2.
Listing 12-2. Running Valgrind with code Listing 12-1
$ valgrind ./stackoverflow
==4188== Memcheck, a memory error detector
...
==4188== Invalid write of size 4
==4188==
at 0x400556: main (stackoverflow.c:36)
==4188== Address 0x51f91d0 is 0 bytes after a block of size 400 alloc'd
==4188==
at 0x4C2EB37: malloc (vg_replace_malloc.c:299)
==4188==
by 0x400547: main (stackoverflow.c:35)
...
==4188== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
Because Valgrind can produce long reports, we show only the relevant “Invalid write”
error part of the report. When compiling code with symbol information (gcc -g), it is
easy to see the exact place in the code where the error is detected. In this case, Valgrind
highlights line 36 of the stackoverflow.c file. With the issue identified in the code, we
know where to fix it.
Memory Leak Example
Memory leaks are another common issue. Consider the code in Listing 12-3.
Listing 12-3. leak.c: Example of a memory leak
32 #include
33
34 void func(void) {
Chapter 12 Debugging persistent MeMory appliCations
Précédent

- 233/457

Suivant