C
Beginner
1 min read
Memory Leaks and Valgrind
Example
/*
* memory_demo.c — illustrates common memory errors and how
* to detect them with Valgrind / AddressSanitizer.
*
* Compile clean (no errors):
* gcc -Wall -Wextra -std=c11 -g memory_demo.c -o memory_demo
*
* Check with Valgrind:
* valgrind --leak-check=full ./memory_demo
*
* Check with AddressSanitizer:
* gcc -fsanitize=address -g memory_demo.c -o memory_demo_asan
* ./memory_demo_asan
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
/* --- LEAK EXAMPLE (intentional for demo) --- */
int *leaked = malloc(64 * sizeof(int));
/* No free(leaked) — Valgrind will report this */
/* --- CORRECT allocation/free --- */
char *msg = malloc(32);
if (!msg) return EXIT_FAILURE;
strncpy(msg, "Hello from heap", 31);
msg[31] = '\0';
printf("%s\n", msg);
free(msg);
msg = NULL; /* good habit: NULL after free */
/* --- DOUBLE-FREE (commented out — UB!) --- */
/* free(msg); <-- would be double-free since msg is now NULL (safe) */
/* free(leaked); free(leaked); <-- actual double-free */
/* --- USE-AFTER-FREE (commented out — UB!) --- */
/* free(leaked); printf("%d\n", leaked[0]); <-- UB */
/* Clean up the leaked pointer so the demo actually runs clean */
free(leaked);
printf("Done. Run under valgrind for memory analysis.\n");
return EXIT_SUCCESS;
}