C Memory


Memory is one of the most crucial concepts in C programming. Every variable, array, and function in a program occupies memory while the program is running. Understanding memory in C not only helps you write efficient programs but also prevents errors like crashes, memory leaks, or unexpected behavior. In this tutorial, we will cover memory types, pointers, dynamic allocation, common issues, and best practices in a detailed, hands-on manner.

Memory Layout in C Programs

When a C program runs, its memory is divided into several segments. Each segment has a specific purpose and lifetime:

  1. Code Segment (Text Segment)
    This segment stores the compiled instructions of the program. It is usually read-only to prevent accidental modification of code. For example:

void hello() {
    printf("Hello, World!\n");
}

The instructions for hello() reside in the code segment. Attempting to change these instructions at runtime would cause a program crash.

  1. Data Segment
    This segment stores global and static variables. It has two parts:

    • Initialized Data Segment: Contains global or static variables that have initial values, e.g., int counter = 5;. These values remain constant unless explicitly changed.

    • Uninitialized Data Segment (BSS): Contains global or static variables declared but not initialized, e.g., static int total;. The system automatically sets them to zero at program start.

  2. Heap
    The heap is used for dynamic memory allocation. Unlike the data segment, memory here can grow or shrink during runtime. You allocate memory on the heap using malloc(), calloc(), or realloc(), and you must free it using free() to avoid memory leaks. Heap memory is ideal for large data structures like arrays, linked lists, or trees when the size is unknown at compile time.

  3. Stack
    The stack stores local variables and function call information like return addresses and function parameters. It follows a last-in-first-out (LIFO) order. Each function call creates a stack frame, which is removed when the function ends. Excessive recursion or allocating too many large local variables can lead to a stack overflow.

Understanding these memory segments helps you determine where variables live and how long they last. Global and static variables persist for the entire program, local variables exist only during function execution, and heap variables persist until freed manually.

Pointers – Accessing Memory Directly

Pointers are variables that store memory addresses. They allow you to access and manipulate memory directly. For example:

int age = 25;
int *ptr = &age;

printf("Age: %d\n", *ptr); // Access value using pointer
*ptr = 30;                  // Modify value through pointer
printf("New Age: %d\n", age);

Pointers are essential for dynamic memory, arrays, and data structures like linked lists, stacks, and trees. However, incorrect pointer use, like dereferencing uninitialized pointers or using freed memory, can lead to crashes or segmentation faults.

Dynamic Memory Allocation

C provides functions to allocate memory at runtime:

  1. malloc() – Allocates memory without initializing it:

int *arr = (int*)malloc(5 * sizeof(int));
  1. calloc() – Allocates memory and initializes it to zero:

int *arr = (int*)calloc(5, sizeof(int));
  1. realloc() – Resizes previously allocated memory:

arr = (int*)realloc(arr, 10 * sizeof(int));
  1. free() – Frees memory on the heap:

free(arr);

Dynamic memory allows programs to be flexible and efficient. Without it, you would need to predefine large arrays, wasting memory if not fully used.

Stack vs Heap – Key Differences

Feature Stack Heap
Lifetime Temporary (function scope) Until explicitly freed
Management Automatic Manual (malloc/free)
Size Limit Smaller (OS-dependent) Larger
Allocation Speed Fast Slower
Common Use Local variables Dynamic data structures

Understanding the difference helps you choose where to store variables. Stack is perfect for small temporary data, while heap suits large or dynamic structures.

Common Memory Issues

Even experienced programmers can encounter memory problems in C:

  • Memory Leaks: Forgetting to free heap memory causes wasted resources.

  • Dangling Pointers: Accessing memory after it’s freed can cause crashes or unpredictable behavior.

  • Buffer Overflows: Writing beyond allocated memory corrupts data or crashes the program.

  • Stack Overflow: Using too much stack memory, often via deep recursion.

Using debugging tools like Valgrind or AddressSanitizer helps detect these issues early.

Understanding Memory Sizes

Different data types occupy different amounts of memory. Typical sizes (may vary by system) are:

Data Type Size (Bytes)
char 1
int 4
float 4
double 8
pointer 4 or 8

Pointer arithmetic depends on data type. For example, if int *p points to memory address 1000, p + 1 points to 1004 (assuming sizeof(int) = 4). Proper understanding of sizes prevents errors in arrays and memory manipulation.

Hands-On Example

Here’s a practical example demonstrating stack and heap memory:

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

void demoMemory() {
    int localVar = 10;                 // Stack variable
    int *heapVar = (int*)malloc(sizeof(int)); // Heap variable

    if(heapVar == NULL) {
        printf("Memory allocation failed\n");
        return;
    }

    *heapVar = 20;
    printf("Stack variable: %d\n", localVar);
    printf("Heap variable: %d\n", *heapVar);

    free(heapVar); // Free heap memory
}

int main() {
    demoMemory();
    return 0;
}

This program shows the difference between stack and heap. localVar exists only while demoMemory() runs, while heapVar remains until freed.

Best Practices for Memory Management

  • Always initialize pointers.

  • Free heap memory when done.

  • Prefer local variables for temporary data.

  • Use heap for large or flexible data.

  • Avoid excessive global variables.

  • Use memory-checking tools during development.

Proper memory management makes programs safer, faster, and easier to debug.

Summary of the Tutorial

Memory is a core aspect of C programming. Understanding how stack, heap, global, and static memory works, along with pointers and dynamic allocation, allows programmers to write efficient and reliable code. C gives you control over memory, but with that control comes responsibility. Learning to manage memory carefully helps avoid errors, improve performance, and become a skilled C programmer.


Practice Questions

  1. Write a program that declares three local variables in a function. Print their values and memory addresses. Call the function multiple times and observe how the addresses change.

  2. Create a program with a global variable and a local variable of the same name. Print both values inside a function and in main(). Explain which variable is accessed in each case.

  3. Declare an integer variable and a pointer to it. Use the pointer to print the variable’s value, modify it, and print the updated value.

  4. Allocate an integer array of size 5 using malloc(). Assign values to the array, print them, and then free the memory.

  5. Allocate an integer array of size 5 using calloc(). Print all values without initializing them manually and observe the output.

  6. Allocate an array of 3 integers using malloc(). Assign values and print them. Then use realloc() to increase the array size to 6. Add new values and print the complete array. Free the memory afterward.

  7. Write a program that allocates memory dynamically, frees it, and then tries to access the freed memory. Observe and explain the behavior.

  8. Write a program that declares a large local array (stack) and a dynamically allocated array (heap). Print their addresses and sizes. Compare the differences.

  9. Create an integer array of size 5. Use a pointer to traverse the array and print each element using pointer arithmetic.

  10. Write a program that allocates memory multiple times without freeing it. Run it with a memory-checking tool like Valgrind to detect memory leaks. Then modify the program to free all allocated memory and confirm the leak is resolved.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top