Building a Dynamic Array in C: A Deep Dive into Memory Management

Dynamic arrays are one of the most fundamental data structures in programming, yet they're not built into C like they are in higher-level languages. Today, we'll explore how to implement a dynamic array from scratch in C, understanding the underlying memory management principles that make it work.

What is a Dynamic Array?

A dynamic array is a data structure that can grow or shrink in size during runtime, unlike static arrays whose size must be determined at compile time. This flexibility makes them incredibly useful for situations where you don't know how much data you'll need to store beforehand.

The Structure Foundation

Our implementation starts with a simple but powerful structure:

#define initialCap 2

typedef struct
{
    int *data;
    int size;
    int capacity;
} DynamicArray;

This structure contains three crucial components:

  • data: A pointer to the actual array elements stored in heap memory
  • size: The current number of elements in the array
  • capacity: The maximum number of elements the array can hold before needing to resize

The distinction between size and capacity is key to understanding how dynamic arrays achieve efficiency. We don't resize the array every time we add an element; instead, we allocate extra space and only resize when necessary.

Initialization: Setting Up for Success

void initArray(DynamicArray *array)
{
    array->data = (int *)malloc(initialCap * sizeof(int));
    array->size = 0;
    array->capacity = initialCap;
}

The initialization function allocates memory for our initial capacity (defined as 2) and sets up the tracking variables. Starting with a small initial capacity keeps memory usage efficient while still providing room for growth.

The Heart of Dynamic Behavior: Resizing

void resizeArr(DynamicArray *array)
{
    int newCap = array->capacity * 2;
    int *newData = (int *)realloc(array->data, newCap * sizeof(int));

    if (newData == NULL)
    {
        fprintf(stderr, "Reallocation failed\n");
        exit(1);
    }

    array->data = newData;
    array->capacity = newCap;
}

This is where the magic happens. When we run out of space, we double the capacity using realloc(). This doubling strategy is crucial for performance:

  • Time Complexity: Doubling ensures that resize operations happen infrequently enough to maintain O(1) amortized time for insertions
  • Space Efficiency: We don't waste too much memory by over-allocating
  • Error Handling: We check if reallocation failed and handle it gracefully

Adding Elements Efficiently

void addElem(DynamicArray *array, int value)
{
    if (array->size == array->capacity)
    {
        resizeArr(array);
    }
    array->data[array->size++] = value;
}

The addElem function demonstrates the beauty of this design. Most of the time, adding an element is just a simple assignment operation. Only when we've reached capacity do we need to resize, making the average case very fast.

Seeing It in Action

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

#define initialCap 2

typedef struct
{
    int *data;
    int size;
    int capacity;
} DynamicArray;

void initArray(DynamicArray *array)
{
    array->data = (int *)malloc(initialCap * sizeof(int));
    array->size = 0;
    array->capacity = initialCap;
}

void resizeArr(DynamicArray *array)
{
    int newCap = array->capacity * 2;
    int *newData = (int *)realloc(array->data, newCap * sizeof(int));

    if (newData == NULL)
    {
        fprintf(stderr, "Reallocation failed\n");
        exit(1);
    }

    array->data = newData;
    array->capacity = newCap;
}

void addElem(DynamicArray *array, int value)
{
    if (array->size == array->capacity)
    {
        resizeArr(array);
    }
    array->data[array->size++] = value;
}

void printArray(DynamicArray *array)
{
    for (int i = 0; i < array->size; i++)
    {
        printf("%d ", array->data[i]);
    }
}

int main() {
    DynamicArray arr;
    initArray(&arr);

    for (int i = 1; i <= 10; i++) {
        addElem(&arr, i * 10);
        printArray(&arr);
        printf("\n");
    }

    free(arr.data);
    return 0;
}

This code will output:

10 
10 20 
10 20 30 
10 20 30 40 
10 20 30 40 50 
10 20 30 40 50 60 
10 20 30 40 50 60 70 
10 20 30 40 50 60 70 80 
10 20 30 40 50 60 70 80 90 
10 20 30 40 50 60 70 80 90 100 

Notice how the array seamlessly grows from an initial capacity of 2 to accommodate all 10 elements, with resize operations happening behind the scenes.

Key Concepts and Best Practices

Memory Management

  • Always check for allocation failures
  • Free allocated memory when done (free(arr.data))
  • Use realloc() for resizing to potentially avoid copying data

Performance Considerations

  • Amortized O(1) insertion: While individual insertions might trigger O(n) resize operations, the average case is constant time
  • Doubling strategy: Balances memory usage with performance
  • Contiguous memory: Better cache locality compared to linked structures

Real-World Applications

Dynamic arrays are everywhere in programming:

  • std::vector in C++: Uses the same principles
  • Python lists: Dynamic arrays under the hood
  • JavaScript arrays: Similar resizing behavior
  • Database query results: Unknown result set sizes

Potential Improvements

While our implementation works well, production code might include:

  • Generic types: Using void* to store any data type
  • Shrinking: Reducing capacity when size drops significantly
  • Custom growth factors: Different strategies for different use cases
  • Error recovery: More sophisticated error handling

Our dynamic array strikes an excellent balance for most use cases, providing the flexibility of dynamic sizing with the performance characteristics of array access.

Comments

Popular posts from this blog

The Bug That Taught Me Cryptography Isn't Enough: How Flawed API Logic Can Destroy a Secure Vault

Learning IPv6 in Cisco Packet Tracer: From Direct Connections to Routed Networks