How to use malloc() and free() in C

Dynamic memory allocation

When an array is defined, memory is allocated in contagious memory blocks according to the specified size before run-time. This might introduce some limitations because of insufficient storage or wastage of space due to unused memory.

Dynamic memory allocation provides a solution to this problem by allowing us to allocate memory during run-time instead of allocating memory ahead of time. This helps us avoid running into insufficient memory and makes us use the memory space efficiently.

In the C programming language, two of the functions used to allocate and deallocate the memory during run-time are malloc() and free(), respectively.

malloc()

The malloc() function is defined in the header <stdlib.h> and allows us to allocate memory during run-time. The function takes the input as size in bytes and returns a void pointer that can be cast to any other type on the successful allocation of memory. The pointer void points to the first byte of the allocated memory. If the memory allocation is not successful, the pointer returns NULL.

Take a look at the line of code below:

ptr = (float *) malloc (10 * sizeof(float));

The line of code above reserves 40 bytes of contagious memory. The size of one float datatype is 4 bytes, which when multiplied by 10 gives 40. The void pointer returned by the malloc() is casted to the type float and assigned to ptr. Therefore, pointer ptr is of type float and points to the first byte of the 40 bytes.

free()

The memory allocated during run-time does not get free on its own. The free() function is used to manually free the memory allocated at run-time. The free() function is defined in the same <stdlib.h> header. The function takes a pointer and frees the memory the pointer is pointing towards.

Using the free() function is simple, as shown below:

free(ptr);

The function simply takes the pointer ptr and deallocates the memory it points towards.

Let’s take a look at a simple example where we use malloc() and free() to allocate memory during run time:

#include<stdio.h>
#include<stdlib.h>
int main()
{
int *ptr;
ptr = (int *)malloc(sizeof(ptr));
if (ptr == NULL)
{
printf("ERROR: could not be allocated: memory overflow\n");
return 1;
}
*ptr = 10;
printf("%d\n", *ptr);
free(ptr);
return 0;
}

Line 6 defines a pointer ptr of type int. The size of ptr is 8 bytes here, which is passed to the malloc() function in Line 7. The void pointer returned by malloc() is typecasted to int. Line 8 checks if the memory is allocated successfully. If not, then an error message is displayed. We assign a value to the location where ptr is pointing. After printing the value, we free the memory using free(ptr) in Line 15.

Copyright ©2024 Educative, Inc. All rights reserved