1. Mastering Bitwise Operators in C: A Comprehensive Guide with Examples - Codzify 2. Ternary Operators in C Programming: A Beginners Guide (2023) 3. Switch Statements in C 2023: Complete Guide for Beginners 4. Learn Functions in C Programming - A Complete Tutorial for Beginners in 2023 5. Call by Value and Call by Reference in C Programming - A Complete Tutorial for Beginners in 2023 6. Storage Classes in C Programming: A Comprehensive Guide for 2023 7. Arrays in C Programming: A Comprehensive Guide for 2023 8. Basics of 2D Array in C Programming in 2023: Definition, Initialization, and Accessing Elements 9. Beginners Guide to Strings in C Programming with Codes and Examples 10. Strings Functions in C Language - strlen, strcpy,strcmp,strcat functions 11. A Comprehensive Guide to Structures in C Programming in 2023 12. Learn Unions in C Programming with Codes, Examples, and Explanations in 2023 13. Dynamic Memory Allocation in C: Understanding malloc, calloc, realloc, and free Functions 14. Introduction to C Programming 15. Hello world program in C 16. String functions in C - strncat, strcpy, strncpy, strchr, strrchr, strstr functions 17. Program for Fibonacci number in C - Codzify.com 18. What is palindrome number in C? 19. Write a C program to find a factorial of a given number 20. Write a C program to check whether a given number is prime or not 21. Write a C program to check whether a given number is an Armstrong number or not. 22. Write a C Program to transpose a matrix 23. C Programming Tutorial: Understanding Comments and Identifiers with Code Examples 24. Master String Handling Functions in C in 2023 - Codzify Topics

Dynamic Memory Allocation in C: Understanding malloc, calloc, realloc, and free Functions

Article by: Manish Methani

Last Updated: October 28, 2021 at 2:04pm IST
5 min 41 sec read

Dynamic memory allocation in C is a powerful feature that allows you to allocate memory at runtime. In this tutorial, we will cover three important functions for dynamic memory allocation in C: malloc, calloc, and realloc. We will explain how to allocate and deallocate memory using these functions, and provide practical examples to help you understand how to use them in your own code.

malloc():

The malloc function is used to allocate memory dynamically in C. It takes one argument, which is the number of bytes to allocate and returns a void pointer to the first byte of the allocated memory. Here is an example of how to use malloc to allocate memory:

#include 
#include 

int main() {
    int* ptr;
    ptr = (int*) malloc(5 * sizeof(int));
    if (ptr == NULL) {
        printf("Memory allocation failed
");
        exit(1);
    }
    for (int i = 0; i < 5; i++) {
        ptr[i] = i + 1;
    }
    for (int i = 0; i < 5; i++) {
        printf("%d ", ptr[i]);
    }
    free(ptr);
    return 0;
}

In the above example, we allocate memory for an array of 5 integers using malloc, check if the memory allocation was successful, fill the array with values using a loop, print the values using another loop, and finally deallocate the memory using the free function.

calloc():

The calloc function is similar to malloc, but it initializes the allocated memory to zero. It takes two arguments, which are the number of elements to allocate and the size of each element in bytes. It returns a void pointer to the first byte of the allocated memory. Here is an example of how to use calloc to allocate memory:

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

int main() {
    int* ptr;
    ptr = (int*) calloc(5, sizeof(int));
    if (ptr == NULL) {
        printf("Memory allocation failed");
        exit(1);
    }
    for (int i = 0; i < 5; i++) {
        printf("%d ", ptr[i]);
    }
    free(ptr);
    return 0;
}

In the above example, we allocate memory for an array of 5 integers using calloc, check if the memory allocation was successful, and print the values in the array. Since calloc initializes the allocated memory to zero, the values printed will be 0.

realloc():

The realloc function is used to resize previously allocated memory. It takes two arguments, which are a pointer to the previously allocated memory and the new size of the memory block in bytes. It returns a void pointer to the new block of memory. Here is an example of how to use realloc to resize previously allocated memory:

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

int main() {
    int* ptr;
    ptr = (int*) malloc(5 * sizeof(int));
    if (ptr == NULL) {
        printf("Memory allocation failed");
        exit(1);
    }
    for (int i = 0; i < 5; i++) {
        ptr[i] = i + 1;
    }
    ptr = (int*) realloc(ptr, 10 * sizeof(int));
    if (ptr == NULL) {
        printf("Memory reallocation failed");
        exit(1);
    }
    for (int i = 5; i < 10; i++) {
        ptr[i] = i + 1;
    }
    for (int i = 0; i < 10; i++) {
        printf("%d ", ptr[i]);
    }
    free(ptr);
    return 0;
}

In the above example, we first allocate memory for an array of 5 integers using malloc, check if the memory allocation was successful, fill the array with values using a loop, and print the values using another loop. We then use realloc to resize the previously allocated memory to 10 integers, check if the reallocation was successful, fill the remaining 5 integers in the array with values using a loop, and print the updated values using another loop. Finally, we deallocate the memory using the free function.

In conclusion, the C programming language provides a powerful set of functions for dynamic memory allocation and deallocation. The malloc, calloc, realloc, and free functions can be used to allocate and deallocate memory at runtime, allowing for efficient use of memory resources. Understanding how to use these functions effectively is essential for any C programmer.

In this tutorial, we have covered the basic concepts of dynamic memory allocation and how to use the malloc, calloc, realloc, and free functions in C. We have explained the differences between these functions and provided practical examples to demonstrate their usage. We hope this tutorial has helped you gain a better understanding of dynamic memory allocation in C and how to use these functions to manage memory effectively in your own code. Remember to always check for errors and handle them appropriately when using these functions. Happy coding!

Learn to Build 5 Apps Without Coding using FlutterFlow

  • Lifetime access to all the 5 FlutterFlow Courses
  • Complete FlutterFlow training
  • All future course updates
  • Access via Codzify mobile app
  • 24h 42m of Learning Content
  • 5 FlutterFlow at Codzify just ₹1500 ($17.44)
  • Access to Dating App Course, Grocery App Course, Courses App Course, FlutterFlow AI Agents Course, Doctor Appointment Booking Supabase Course.
  • Clone Ready-Made Courses App instantly in FlutterFlow.
  • Non-Refundable once you get the access to Courses

Learn More
Codzify Logo

Terms and Conditions    Cookie Policy   Refund Policy   Adsense Disclaimer

Contact: [email protected]