DEV Community

Ujjawal Chaudhary
Ujjawal Chaudhary

Posted on

With Great Power Comes Great Responsibility (and Segfaults) 🧠

Day 3/30: Stack vs. Heap.

On the Stack, variables are cleaned up automatically when a function ends. It's safe, but limited in size.

On the Heap (using malloc), you can allocate massive amounts of memory that persist as long as you want. But there is a catch: You are the Garbage Collector.

The Rule of Thumb: For every malloc() you write, write the free() immediately.
If you forget, that memory block stays occupied until your program dies. Do this enough times in a long-running server, and you crash the system.

Today was all about learning to borrow resources and ensuring I return them.

The Code

Here is the C code for Day 3:



// Day 3: The Danger of the Heap

#include <stdio.h>
#include <stdlib.h> // Required for malloc/free

void dangerous_function() {
    // Requesting memory from the Heap
    // This lives outside the function's scope
    // 100 integers * 4 bytes = 400 bytes allocated
    int *data = (int*)malloc(100 * sizeof(int));

    // Always check if the OS actually gave you the memory
    if (data == NULL) {
        printf("Memory allocation failed!\n");
        return; 
    }

    // ... process data ...
    data[0] = 42;
    printf("Heap memory allocated. Value: %d\n", data[0]);

    // CRITICAL: If you forget this, the memory 
    // remains "occupied" forever (Memory Leak)
    free(data); 

    // Good practice: Remove the dangling pointer
    // so you don't accidentally use it again
    data = NULL;
    printf("Heap memory freed.\n");
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)