malloc & free

malloc & free

Dynamic memory allocation

“Who in the world is malloc and where are they located and why do they need to be freed?”, was my first thought when the topic malloc & free was introduced in a c programming course I was “shadowing“. This post will delve into how malloc is indeed a function (not a who) and the need to free allocated memory after making use of it.

Introduction

Effective programming necessitates proper memory allocation and management. This article focuses on dynamic memory allocation and introduces the C functions malloc and free. Additionally, it provides a detailed walkthrough of successfully implementing these concepts.

Dynamic Memory Allocation with malloc and free:

Dynamic memory allocation allows us to allocate and deallocate memory during program execution.

  1. The malloc function:

The malloc function in C reserves a block of memory of a specified size and returns a pointer to the beginning of that block. Here’s an example:

int * dynamicArray = (int*) malloc(5 * sizeof(int));

In this code, malloc allocates memory for an array of 5 integers. The returned pointer is cast to an int* to match the data type.

Reminder (ᵔ◡ᵔ): always include the <stdlib.h> header file for the malloc function.

  1. The free function:

The free function deallocates memory previously allocated using malloc. Here’s an example:

free(dynamicArray);

In this code, free releases the memory allocated for the dynamicArray. It’s essential to call free for every dynamically allocated memory block to prevent memory leaks.

memory allocation illustration

Benefits of Dynamic Memory Allocation:

Let’s understand why and when we should use dynamic memory allocation

  1. Unknown Data Size:

When the size of the data is unknown or varies during runtime, dynamic allocation becomes essential. For instance, when reading user input or data from a file, malloc enables us to allocate memory based on the input size.

  1. Resource Efficiency:

Allocating memory dynamically ensures efficient memory utilization. Instead of declaring multiple fixed-size variables, dynamic allocation lets us optimise memory usage by allocating memory as needed.

Understanding dynamic memory allocation, malloc and free functions are fundamental skills in C programming. By applying these concepts and tools, we can efficiently manage memory resources, optimize program efficiency, and build robust and reliable applications. Here is a practical example of dynamic memory allocation:

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

/**
* main - Entry 
*
* Return: nothing
*/

int mai()
{

    int i;
    int *dynamicArray;

    /* Allocate memory for an array of 5 integers */
    dynamicAray = (int*) malloc(5 * sizeof(int));

    /* Check if allocation was successful */
    if (dynamicArray == NULL)
    {
         return (0);
    }

    /* Assign values to the dynamic array */
    for (i = 0; i < 5; i++)
    {
        dynamicArray[i] = i + 1;
    }

    /* Print the array */
    for (i = 0; i < 5; i++)
    {
        printf("%d", dynamicArray[i]);
    }
    printf("\n");

    /* Free the dynamically allocated memory */
    free(dynamicArray);

    return (0);
}

In this example, memory was allocated for an array of 5 integers using malloc. Values to the array were then assigned and printed. And in the final step, the dynamically allocated memory was freed using the free function.

Takeway (๑ᵔ⤙ᵔ๑):

  • malloc allocates the requested number of bytes and returns a pointer to the first byte of the allocated space.
General format
ptr = (type *) malloc(byte_size);
  • free frees up previousely allocated space
General format
free(ptr);

Conclusion

In programming, dynamic memory allocation is a powerful technique that enables programmers to allocate and deallocate memory during program execution. By using the malloc function, one can dynamically allocate memory, using the free function helps in releasing that memory when it is no longer needed. When dealing with unknown data sizes or creating dynamic data structures, this flexibility becomes especially valuable.

Thank you for reading. Happy Coding!