System Environment
- Ubuntu 22.10 kinetic
Introduction
Valgrind is a suite of debugging tools for Linux, commonly used to detect memory leaks, illegal reads/writes, and other issues in programs.
Wikipedia - Valgrind - Wikipedia
This article focuses on Memcheck, which can be used to check for memory leaks in programs.
Installing Valgrind
Official download page - Valgrind Download
sudo apt update && apt full-upgrade -y
sudo apt install valgrind -y
valgrind --version
Usage
valgrind ./<filename>
valgrind --leak-check=<no|summary|yes|full> [default: summary]
Common Errors
1. Illegal Read/Write Error
#include <stdio.h>
int main(){
int *ptr = 0;
*ptr = 0;
return 0;
}
gcc -g -O0 test.c -o test
./test
[1] 7453 segmentation fault (core dumped) ./test
valgrind ./test
==7484== Memcheck, a memory error detector
==7484== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==7484== Using Valgrind-3.18.1 and LibVEX; rerun with -h for copyright info
==7484== Command: ./test
==7484==
==7484== Invalid write of size 4
==7484== at 0x10913D: main (test.c:4)
==7484== Address 0x0 is not stack'd, malloc'd or (recently) free'd
2. Accessing Uninitialized Values
#include <stdio.h>
int main(){
int x;
printf ("x = %d\n", x);
}
3. Using Uninitialized or Non-Addressable Values in System Calls
4. Illegal Memory Deallocation
5. Mismatched Operators
If memory is allocated with malloc/calloc/realloc/valloc/memalign, it must be freed with free.
If memory is allocated with new, it must be freed with delete.
If memory is allocated with new[], it must be freed with delete[].
Note that running such a program on Linux may not cause any issues, but it could crash on other platforms.
6. Memory Overlapping Error
(Memory Overlapping Error)
Memory overlap errors can occur when using memcpy, strcpy, strncpy, strcat, strncat
7. Fishy Argument Values
(Fishy argument values)