Reprinted please indicate the source and the author contact: http://blog.csdn.net/mimepp
Contact information: Yu Tao <yut616 at Sohu dot com>
Here we will record various potential error messages in your application using valgrind and give examples.
Valgrind is often used to find out memory-related errors of your code, which is of great significance for system stability after porting to the embedded system.
Usage
- X86 Platform
- Compile your own application first
- Command line:
- Valgrind -- log-file = 1 -- tool = memcheck./A. Out
Error Specification
1. There is malloc, but not free
- Code
#include <stdio.h>
#include <stdlib.h>
void main()
{
char *p = malloc(20);
sprintf(p, "%s", "test");
fprintf(stderr, "p:%s/n", p);
}
- Analysis:
- At the back of the file, there are definitely 20 bytes of lost. As follows:
==26512== LEAK SUMMARY:
==26512== definitely lost: 20 bytes in 1 blocks.
- The content described earlier in the file shows that there is one malloc, but it is not free. As follows:
==26512== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 11 from 1)
==26512== malloc/free: in use at exit: 20 bytes in 1 blocks.
==26512== malloc/free: 1 allocs, 0 frees, 20 bytes allocated.
2. Free a pointer without malloc
3. In the stack, the read is invalid and no error is prompted.
- Code
Void main ()
{
Char P [8] = "hello"; // P on the stack, "hello" in the constant area
Fprintf (stderr, "P10: % C/N", P [10]);
}
- Analysis:
- It is a local variable and is stored in the stack. Since P [10] does not exceed the stack length, no error is prompted?
4. If the heap is invalid, an error is prompted.
5. Invalid write on the stack
6. Heap stack, invalid write