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

Explore Codzify Courses

PREMIUM

Learn to create the Dating App using No-Code Tool FlutterFlow

Level: Advanced

Course Fees: INR 6999/-

Apply Coupon Code: UNLOCK

4 days 100% Money Back Guarantee

Explore Curriculum
PREMIUM

Flutter Mobile App Development Course

Level: Intermediate

Course Fees: INR 1299/-

4 days 100% Money Back Guarantee

Explore Curriculum
PREMIUM

The Complete Angular Course

Level: Beginners

Course Fees: INR 1299/-

4 days 100% Money Back Guarantee

Explore Curriculum
PREMIUM

Dart Programming for Absolute Beginners

Level: Beginners

Course Fees: INR 1299/-

4 days 100% Money Back Guarantee

Coming Soon
FREE

Next.js course

Level: Beginners

Course Fees: FREE

Start Watching
FREE

Fundamentals of Computer Programming Languages

Level: Beginners

Course Fees: FREE

Start Watching
FREE

Learn HTML, CSS & Bootstrap

Level: Beginners

Course Fees: FREE

Start Watching

Latest Web Stories

1

Learn how to open WhatsApp using FlutterFlow | Step by Step Guide

Test your skills with these expert-led curated
Mock Tests.

C Programming Test

Test your C Programming skills with this comprehensive mock test on C Programming.

Take Test

Flutter Test

Solve most asked Interview Questions on Flutter and Test your foundational skills in flutter.

Take Test

GATE(CSE) Operating Systems

Solve most asked GATE Questions in Operating Systems and test your Gate Score.

Take Test

HTML,CSS Test

This is a mock test designed to help you assess your knowledge and skills in HTML and CSS.

Take Test

(GATE CSE) Data Structures & Algorithms Test

Solve most asked GATE Questions in Data Structures and Algorithms and test your Gate Score.

Take Test

Download the Codzify
Mobile App


Learn Anytime, Anywhere at your own pace. Scan the QR Code with your Mobile Camera to Download the Codzify Mobile App.

Codzify Mobile App Codzify Mobile App
Codzify Logo

Terms and Conditions    Cookie Policy   Refund Policy   Adsense Disclaimer