Course contentsShow
← C
Lesson 987 of 1,21914. Data Structures in CFree lesson

Popping and shrinking logic

Popping and shrinking logic

What you'll learn: How to remove the last element from a dynamic array and efficiently manage memory by shrinking the capacity when it's no longer needed.

The "Empty Seats" Problem

In previous lessons, we learned that when a dynamic array runs out of room, we use realloc to double its size. But what happens when you start removing items? If you add 1,000 items and then delete 999 of them, your array is still hogging enough memory for 1,000 items while only using one. This is like keeping a massive wedding marquee standing for a party of two—it’s a waste of space.

The Popping Logic

"Popping" is the simplest way to remove data: we just delete the very last item. In C, we don't actually have to erase the data in memory. We simply decrement our size variable. The program now "forgets" that the last slot exists.

When to Shrink

To keep our memory usage lean, we want to shrink the array (using realloc again) when it becomes mostly empty. However, there is a catch: if you shrink the array the moment it is half-empty, and the user immediately adds one more item, you’ll have to expand it again. This "back-and-forth" resizing is slow.

A common industry standard is the Quarter-Rule: only shrink the capacity by half when the size drops to one-quarter of the capacity. This provides a "buffer" so your program isn't constantly resizing.

The Code in Action

Here is how you handle the logic of removing an element and checking if it's time to downsize.

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

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

void pop(DynamicArray *arr) {
    if (arr->size == 0) return;

    // 1. "Remove" the item by decreasing size
    arr->size--;

    // 2. Check if we should shrink (Quarter-Rule)
    // If we are using only 25% of capacity, cut capacity in half
    if (arr->size > 0 && arr->size <= arr->capacity / 4) {
        int newCapacity = arr->capacity / 2;
        int *temp = realloc(arr->data, newCapacity * sizeof(int));
        
        if (temp) {
            arr->data = temp;
            arr->capacity = newCapacity;
            printf("Shrunk capacity to %d\n", arr->capacity);
        }
    }
}

Efficiency vs. Memory

By shrinking, you ensure your program remains a "good citizen" of the operating system, returning memory you aren't using. By using the Quarter-Rule instead of shrinking immediately, you ensure your program remains fast.

Key takeaway

To pop an element, decrement the size; to save memory, use realloc to halve the capacity only when the array is 25% full.