Desperately Freeing Allocated Memory

The critical issue about allocating and then freeing memory is to avoid a memory leak. This condition happens when a memory chunk gets lost, leaving the it lingering in RAM not doing anyone any good. Most often a memory leak occurs in a function.

Of course, if the function allocates memory and returns that chunk for some useful purpose — don’t free it! Otherwise, for a temporary buffer, free that memory before the function exits. When you don’t, memory overflows, the system becomes sluggish, the program crashes, and peril portends the planet. These are unwanted things.

The following code features the memory() function, which allocates 1GB chunks and leaves them lingering.

2022_04_23-Lesson-a.c

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

void memory(void)
{
    char *p;

    p = malloc(1024*1024*1024);        /* 1GB */
    if( p==NULL )
    {
        fprintf(stderr,"Unable to allocate memory\n");
        exit(1);
    }
}

int main()
{
    int x;

    for( x=0; x<1024; x++ )
    {
        printf("%4d - Allocating memory: ",x);
        memory();
        printf("done!\n");
    }

    return(0);
}

The for loop in the main() function repeats at least 1,024 times, calling the memory() function over and over. Each time, the memory() function allocates 1GB of RAM and leaves it in memory: lost, unavailable, and unrecoverable.

Theoretically, the program allocates and wastes 1TB of memory if it runs to its conclusion. This memory is recovered when the program quits, of course, but during its run the memory is wasted.

On my Macintosh and under Linux, the program runs to completion. Weird. My Mac has 32GB of RAM installed, not 1TB. So something hinky is going on.

In Windows, the for loop runs 117 times before the malloc() function fails and the program quits (releasing the memory).

This example is extreme, but it works to illustrate how you’re supposed to free memory: In a function, when memory is allocated and no longer needed, use the free() function. (Click here to see the corrected version of the code.)

In the main() function, yes you can free() allocated memory before that final return statement. These statements can appear in any order; you need not free memory in the same sequence (or reverse sequence) by which it was allocated. Freeing memory makes your code pleasing to the pedants who demand such things, but the absence of a parade of free() statements at the end of the main() function isn’t deleterious to the code.

One thought on “Desperately Freeing Allocated Memory

Leave a Reply