C Dynamic Memory Allocation with malloc(), calloc(), realloc() and free()

Hello there! Welcome to this tutorial on “C Dynamic Memory Allocation with malloc(), calloc(), realloc() and free()”. If you’re here, you’re probably curious about how to manage memory dynamically in C. Well, you’re in the right place! Let’s dive in, shall we?

Introduction to Dynamic Memory Allocation in C

First things first, what’s dynamic memory allocation? In C, dynamic memory allocation refers to the process of manually managing memory. This means that you, the programmer, get to decide when and how much memory to allocate or deallocate. This is done using the functions malloc(), calloc(), realloc(), and free(), which are provided under the stdlib library.

Understanding malloc()

malloc(), which stands for “memory allocation”, is used to dynamically allocate a single large block of memory with a specified size. It returns a pointer of type void which can be cast into a pointer of any form. If the space is insufficient, allocation fails and returns a NULL pointer.

Here’s the syntax of malloc() in C:

ptr = (cast-type*) malloc(byte-size)

For example:

ptr = (int*) malloc(100 * sizeof(int));

This statement allocates contiguous space in memory for 100 elements each with the size of the int.

Diving into calloc()

calloc(), which stands for “contiguous allocation”, is very similar to malloc(). The main difference is that calloc() allocates multiple blocks of memory each of the same size and sets all bytes to zero.

Here’s the syntax of calloc() in C:

ptr = (cast-type*)calloc(n, element-size);

For example:

ptr = (float*) calloc(25, sizeof(float));

This statement allocates contiguous space in memory for 25 elements each with the size of the float.

Exploring realloc()

realloc(), which stands for “reallocate”, is used to dynamically change the memory allocation of a previously allocated memory. In other words, if you’ve previously allocated some memory using malloc() or calloc(), and now you need more (or less) memory, you can use realloc() to do that.

Here’s the syntax of realloc() in C:

ptr = realloc(ptr, newSize);

The Role of free()

free() function is used to deallocate the memory that was previously allocated by malloc(), calloc() or realloc() function.

Here’s the syntax of free() in C:

free(ptr);

Code Examples

Let’s look at a couple of complete C codes to understand dynamic memory allocation better.

Code Example 1: Dynamic Array Using malloc() and free()

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

int main() {
    int n, i, *ptr, sum = 0;

    printf("Enter number of elements: ");
    scanf("%d", &n);

    ptr = (int*) malloc(n * sizeof(int));
    if(ptr == NULL)                     
    {
        printf("Error! memory not allocated.");
        exit(0);
    }

    printf("Enter elements: ");
    for(i = 0; i < n; ++i)
    {
        scanf("%d", ptr + i);
        sum += *(ptr + i);
    }

    printf("Sum = %d", sum);

    // deallocating the memory
    free(ptr);

    return 0;
}
C

In this code, we’re using `malloc()to allocate memory for an array of integers, and then we're usingfree()` to deallocate the memory once we’re done with it.

Code Example 2: Dynamic Memory Allocation for a 2D Array

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

int main() {
    int r=3, c=4, i, j, count = 0;
    int **arr = (int **)malloc(r * sizeof(int *));
    for (i=0; i<r; i++)
         arr[i] = (int *)malloc(c * sizeof(int));

    for (i = 0; i <  r; i++)
      for (j = 0; j < c; j++)
         arr[i][j] = ++count;  // OR *(*(arr+i)+j) = ++count

    for (i = 0; i <  r; i++)
      for (j = 0; j < c; j++)
         printf("%d ", arr[i][j]);

   /* Code for further processing and free the 
      dynamically allocated memory */

   return 0;
}
C

In this code, we’re using malloc() to allocate memory for a 2D array of integers.

Wrapping Up

And there you have it! You now know how to use malloc(), calloc(), realloc(), and free() to manage memory dynamically in your C programs. Remember, dynamic memory allocation is a powerful tool in C, and understanding how to use it effectively can make your code more efficient and flexible.

Frequently Asked Questions (FAQ)

  1. What is dynamic memory allocation in C?

    Dynamic memory allocation in C refers to the process of manually managing memory using the functions malloc(), calloc(), realloc(), and free().

  2. What is the difference between malloc() and calloc()?

    The main difference between malloc() and calloc() is that malloc() allocates a single block of memory, while calloc() allocates multiple blocks of memory each of the same size and sets all bytes to zero.

  3. What is the use of realloc()?

    realloc() is used to change the size of the memory block without losing old data. It copies the old memory block to the new location with the new size.

  4. What is the role of free() in dynamic memory allocation?

    free() function is used to deallocate the memory that was previously allocated by malloc(), calloc() or realloc() function.

  1. Understanding Pointers in C
  2. Pointer Arithmetic in C
  3. Pointers with Arrays in C
  4. Pointers with Strings in C
  5. Pointers with Functions in C
Scroll to Top