0
0
Cprogramming~5 mins

Memory leak concepts

Choose your learning style9 modes available
Introduction

A memory leak happens when a program keeps using memory but never gives it back. This can make the program slow or crash.

When writing programs that use dynamic memory (like with malloc).
When you want your program to run smoothly without running out of memory.
When debugging why a program gets slower or crashes after running for a while.
When learning how to manage memory properly in C.
When working on long-running programs like servers or games.
Syntax
C
/* Memory leak example in C */
#include <stdlib.h>
int *ptr = malloc(sizeof(int));
*ptr = 10;
// Forgot to free(ptr);

malloc() reserves memory but does not give it back automatically.

You must use free() to release memory when done.

Examples
This code allocates memory but never frees it, causing a memory leak.
C
#include <stdlib.h>
int *ptr = malloc(sizeof(int));
*ptr = 5;
// No free called here, memory leak occurs
This code correctly frees the memory after use, preventing a leak.
C
#include <stdlib.h>
int *ptr = malloc(sizeof(int));
*ptr = 5;
free(ptr);
Allocating memory for a string but forgetting to free it causes a leak.
C
#include <stdlib.h>
#include <string.h>
char *str = malloc(20 * sizeof(char));
strcpy(str, "hello");
// Missing free(str); causes leak
Sample Program

This program allocates memory for 3 integers, uses them, then frees the memory to avoid a leak.

C
#include <stdio.h>
#include <stdlib.h>

int main() {
    int *numbers = malloc(3 * sizeof(int));
    if (numbers == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }
    numbers[0] = 10;
    numbers[1] = 20;
    numbers[2] = 30;

    printf("Numbers: %d, %d, %d\n", numbers[0], numbers[1], numbers[2]);

    // Forgetting to free here would cause a memory leak
    free(numbers);

    return 0;
}
OutputSuccess
Important Notes

Always pair each malloc() with a free() to avoid leaks.

Memory leaks can cause your program to use more and more memory over time.

Tools like Valgrind can help find memory leaks in your programs.

Summary

Memory leaks happen when allocated memory is not freed.

Use free() to release memory after use.

Preventing leaks keeps programs fast and stable.