HOME HTML EDITOR C JAVA PHP

C Memory Management:

To understand memory management, you must first distinguish between Static Allocation (Stack) and Dynamic Allocation (Heap).

1. Stack vs. Heap: The Core Concept

Most variables you have used so far are stored on the Stack. Their size must be known at compile-time, and they are deleted automatically when the function ends.

The Heap is a large pool of memory that stays allocated until you explicitly free it. This allows you to create data structures like Linked Lists or arrays whose size is determined by user input while the program is running.

2. The Standard Library Functions

All dynamic memory functions are located in the <stdlib.h> header file. There are four primary functions you must master:

A. malloc() – Memory Allocation

malloc stands for "Memory Allocation." It reserves a single block of memory of a specified size in bytes. Crucial Note: It returns a void* (a pointer to an unknown type), so you should cast it to your desired type. It also does not clear the memory; it will contain "garbage values."

// Allocating space for 10 integers
int *ptr = (int*) malloc(10 * sizeof(int));

B. calloc() – Contiguous Allocation

calloc is similar to malloc but is used to allocate multiple blocks of memory. It takes two arguments: the number of elements and the size of each. Key Difference: It initializes all allocated memory to zero.

// Allocating space for 10 integers and setting them to 0
int *ptr = (int*) calloc(10, sizeof(int));

C. realloc() – Re-allocation

If the memory previously allocated is insufficient or more than required, realloc changes the size of the memory block without losing the old data.

// Changing the size of ptr to hold 20 integers instead of 10
ptr = (int*) realloc(ptr, 20 * sizeof(int));

D. free() – De-allocation

This is the most critical function. It releases the memory block back to the heap. If you do not call free, your program will keep consuming memory until the system runs out—this is known as a Memory Leak.

free(ptr);
ptr = NULL; // Setting to NULL prevents "Dangling Pointer" errors

3. The Professional Workflow

When working with the heap, you must follow a strict 4-step process to prevent crashes:

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

int main() {
    int *arr;
    int size = 5;

    // 1. Allocate
    arr = (int*) malloc(size * sizeof(int));

    // 2. Check for Success (MANDATORY)
    if (arr == NULL) {
        printf("Memory Allocation Failed!");
        return 1;
    }

    // 3. Use
    for(int i = 0; i < size; i++) arr[i] = i * 10;

    // 4. Free
    free(arr);
    return 0;
}

4. Common Memory Pitfalls

Dynamic memory is powerful, but dangerous. Watch out for these three bugs:

5. malloc vs calloc: Comparison Table

Feature malloc() calloc()
Initialization Garbage values (Fast). Zero-initialized (Slower).
Number of Args 1 (Total bytes). 2 (Elements, size per element).
Use Case Large single blocks. Arrays or cleared memory.
Pro Tip: When using realloc, always assign the result to a temporary pointer. If realloc fails, it returns NULL, but the original memory is still valid. If you overwrite your original pointer with NULL, you will never be able to free the old memory!