Static and Dynamic Memory Allocation with Example

Memory allocation is a fundamental concept in C programming, essential for managing how data is stored and accessed during program execution. In C, memory allocation can be categorized into three primary types: static, partial dynamic, and full dynamic. Each type has distinct characteristics, advantages, and limitations, making them suitable for different scenarios.

Let’s discuss these three concepts with example:

  • Static Memory Allocation involves fixed-size arrays (i.e. int array[10]) that are determined at compile time.
  • Partial Dynamic Memory Allocation allows for variable-length arrays whose sizes are specified at runtime but stored on the stack.
  • Full Dynamic Memory Allocation offers the greatest flexibility, enabling programs to allocate memory on the heap during execution.

1. Fix (Static) Memory Allocation

Description: Static memory allocation refers to the process of allocating memory at compile time, where the size and layout of the memory are determined before the program starts running. This typically applies to:

  • Local Variables (stored on the stack) when they have a fixed size known at compile time.
  • Global or Static Variables (stored in the data segment) which are allocated memory when the program begins execution and remain for the duration of the program’s lifetime.
#include <stdio.h>
int main() {
    int array[5] = {1, 2, 3, 4, 5}; // Fixed size array declared at compile time
    printf("Static Array Elements:\n");
    for (int i = 0; i < 5; i++) {
        printf("%d ", array[i]);
    }
    printf("\n");
    return 0;
}
Important: In some cases, you may look at the following which is a fixed memory allocation case at compile time int numbers[];  // Array size is inferredNote: “inferred” means that the compiler automatically determines the size of the array based on the number of elements provided in the list.

This works only when we know the values beforehand, like int numbers[] = {1, 2, 3, 4};. However, it does not work when input is provided by the user at runtime (e.g., through scanf), because the compiler cannot anticipate or infer the number of elements before the program runs.

2. Partial Dynamic Memory Allocation

Memory is allocated at runtime (execution time), but it is stored on the stack. This is achieved with variable-length arrays (i.e. using scanf) in C.

Example:

#include <stdio.h>
int main() {
    int n;
    printf("Enter the number of elements: ");
    scanf("%d", &n);
    int array[n]; // VLA: Array size decided at runtime
    printf("Enter %d elements:\n", n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &array[i]);
    }
    printf("Partial Dynamic Array Elements:\n");
    for (int i = 0; i < n; i++) {
        printf("%d ", array[i]);
    }
    printf("\n");
    return 0;
}

3. Full Dynamic Memory Allocation

Description: Memory is allocated at runtime and stored in the heap memory. In C, dynamic memory allocation is done using malloc(), calloc(), realloc(), and free().

Example:

#include <stdio.h>
#include <stdlib.h> // Required for malloc and free
int main() {
    int n;
    printf("Enter the number of elements: ");
    scanf("%d", &n);
    int *array = (int *)malloc(n * sizeof(int)); // Dynamically allocate memory on the heap
    if (array == NULL) {
        printf("Memory allocation failed.\n");
        return 1;
    }
    printf("Enter %d elements:\n", n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &array[i]);
    }
    printf("Fully Dynamic Array Elements:\n");
    for (int i = 0; i < n; i++) {
        printf("%d ", array[i]);
    }
    printf("\n");
    free(array); // Free the allocated memory
    return 0;
}

Summary Table of Static and Dynamic Memory Allocation

Here’s a comprehensive comparison table covering the key differences between static memory allocation, partial dynamic memory allocation, and full dynamic memory allocation in C.

Feature Static Memory Allocation Partial Dynamic Memory Allocation Full Dynamic Memory Allocation
Memory Allocation Time Compile-time Runtime Runtime
Memory Location Stack Stack Heap
Array Size Determination Fixed and known at compile-time Determined at runtime Determined at runtime
Flexibility in Size Not flexible; size is fixed Flexible at runtime, but limited by stack size Fully flexible; large allocations possible (heap-based)
Usage Syntax int array[5]; int array[n]; int *array = malloc(n * sizeof(int));
Memory Deallocation Automatic when function scope ends Automatic when function scope ends Manual; must use free()
Resizing Capability Not possible Not possible Possible by reallocating with realloc()
Compiler Support Supported in all C standards Supported in C99 and later Supported in all C standards
Error Handling Not needed; array size is fixed Not needed; array size is fixed after declaration Needed; must check if malloc()/realloc() succeeds
Risk of Memory Leaks None None Possible if free() is not called
Stack Overflow Risk Low (if size is small and known) Higher (depending on array size at runtime) None (stored on the heap, but high allocations can still exhaust memory)
Example Code int array[5]; int array[n]; int *array = malloc(n * sizeof(int));