Skip to main content
Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Resources
    • Cheatsheets
    • Tech Comparisons
  • Languages
    • Angular Angular js ASP.NET Asp.net Core ASP.NET Core, C# ASP.NET MVC ASP.NET Web Forms C C# C#, ASP.NET Core, Dapper
      C#, ASP.NET Core, Dapper, Entity Framework DotNet General Web Development HTML, CSS HTML/CSS Java JavaScript JavaScript, HTML, CSS JavaScript, Node.js Node.js
      Python Python 3.11, Pandas, SQL Python 3.11, SQL Python 3.11, SQLAlchemy Python 3.11, SQLAlchemy, SQL Python 3.11, SQLite React Security SQL Server TypeScript
  • Post Blog
  • Tools
    • Beautifiers
      JSON Beautifier HTML Beautifier XML Beautifier CSS Beautifier JS Beautifier SQL Formatter
      Dev Utilities
      JWT Decoder Regex Tester Diff Checker Cron Explainer String Escape Hash Generator Password Generator
      Converters
      Base64 Encode/Decode URL Encoder/Decoder JSON to CSV CSV to JSON JSON to TypeScript Markdown to HTML Number Base Converter Timestamp Converter Case Converter
      Generators
      UUID / GUID Generator Lorem Ipsum QR Code Generator Meta Tag Generator
      Image Tools
      Image Converter Image Resizer Image Compressor Image to Base64 PNG to ICO Background Remover Color Picker
      Text & Content
      Word Counter PDF Editor
      SEO & Web
      SEO Analyzer URL Checker World Clock
  1. Home
  2. Blog
  3. C
  4. Dynamic Memory Allocation in C: Understanding malloc, calloc, realloc, and free

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

Date- Mar 11,2026 185
c dynamic memory allocation

Overview of Dynamic Memory Allocation

Dynamic memory allocation is the process of allocating memory during the runtime of a program, allowing for flexible memory usage and efficient resource management. Unlike static memory allocation, which is fixed at compile time, dynamic allocation provides the ability to request memory as needed, which is essential for handling variable data sizes, such as user inputs or large datasets. Using dynamic memory allocation can significantly improve the performance and responsiveness of your applications.

Prerequisites

  • Basic understanding of C programming language
  • Familiarity with pointers in C
  • Knowledge of data types and structures in C
  • Compiling and running C programs

Using malloc for Memory Allocation

malloc (memory allocation) is a standard library function used to allocate a specified amount of memory during the runtime. It returns a pointer to the allocated memory block, which must be cast to the appropriate type.

#include 
#include 

int main() {
    int *arr;
    int n;
    printf("Enter the number of elements: ");
    scanf("%d", &n);

    // Allocating memory for n integers
    arr = (int *)malloc(n * sizeof(int));

    // Checking if memory allocation was successful
    if (arr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }

    // Initializing and displaying the array
    for (int i = 0; i < n; i++) {
        arr[i] = i + 1;
    }

    printf("Array elements: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }

    // Freeing allocated memory
    free(arr);
    return 0;
}

This example demonstrates how to use malloc to allocate memory for an array of integers. Here's a breakdown of the code:

  • #include <stdio.h> and #include <stdlib.h>: Include the standard input/output and standard library headers.
  • int *arr;: Declare a pointer to hold the address of the dynamically allocated memory.
  • int n;: Declare an integer to store the number of elements the user wants.
  • scanf("%d", &n);: Read the number of elements from the user.
  • arr = (int *)malloc(n * sizeof(int));: Allocate memory for n integers and assign the pointer to arr.
  • if (arr == NULL): Check if malloc succeeded in allocating memory.
  • for (int i = 0; i < n; i++) { arr[i] = i + 1; }: Initialize the array with values.
  • free(arr);: Release the allocated memory to prevent memory leaks.

Using calloc for Memory Allocation

calloc (contiguous allocation) is another memory allocation function that allocates memory for an array of elements and initializes all bytes to zero. It takes two parameters: the number of elements and the size of each element.

#include 
#include 

int main() {
    int *arr;
    int n;
    printf("Enter the number of elements: ");
    scanf("%d", &n);

    // Allocating memory for n integers using calloc
    arr = (int *)calloc(n, sizeof(int));

    // Checking if memory allocation was successful
    if (arr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }

    // Displaying the array
    printf("Array elements after calloc: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }

    // Freeing allocated memory
    free(arr);
    return 0;
}

This example illustrates how to use calloc for memory allocation. Here's the explanation:

  • arr = (int *)calloc(n, sizeof(int));: Allocate memory for n integers and initialize them to zero.
  • for (int i = 0; i < n; i++) { printf("%d ", arr[i]); }: Display the initialized array elements, which will all be zero.

Using realloc for Resizing Memory

realloc is used to resize a previously allocated memory block. It can increase or decrease the size of the memory block and may move the memory to a new location if the current block cannot accommodate the new size.

#include 
#include 

int main() {
    int *arr;
    int n;
    printf("Enter the initial number of elements: ");
    scanf("%d", &n);

    // Allocating memory for n integers
    arr = (int *)malloc(n * sizeof(int));

    // Checking if memory allocation was successful
    if (arr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }

    // Initializing the array
    for (int i = 0; i < n; i++) {
        arr[i] = i + 1;
    }

    // Resize the array
    printf("Enter the new size: ");
    int new_size;
    scanf("%d", &new_size);
    arr = (int *)realloc(arr, new_size * sizeof(int));

    // Checking if realloc was successful
    if (arr == NULL) {
        printf("Memory reallocation failed\n");
        return 1;
    }

    // Displaying the resized array
    printf("Array elements after realloc: ");
    for (int i = 0; i < new_size; i++) {
        printf("%d ", arr[i]);
    }

    // Freeing allocated memory
    free(arr);
    return 0;
}

This example demonstrates how to use realloc. Here's the breakdown:

  • arr = (int *)malloc(n * sizeof(int));: Allocate memory for the initial size specified by the user.
  • arr = (int *)realloc(arr, new_size * sizeof(int));: Resize the memory block to the new size provided by the user.
  • if (arr == NULL): Check if the memory reallocation was successful.
  • for (int i = 0; i < new_size; i++) { printf("%d ", arr[i]); }: Display the current elements of the resized array.

Freeing Memory with free

The free function is used to deallocate memory that was previously allocated with malloc, calloc, or realloc. Failing to free dynamically allocated memory can lead to memory leaks.

#include 
#include 

int main() {
    int *arr;
    int n;
    printf("Enter the number of elements: ");
    scanf("%d", &n);

    arr = (int *)malloc(n * sizeof(int));
    if (arr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }

    // Using the array
    for (int i = 0; i < n; i++) {
        arr[i] = i + 1;
    }

    // Freeing allocated memory
    free(arr);
    arr = NULL; // Prevent dangling pointer
    return 0;
}

This example shows the importance of freeing memory:

  • free(arr);: Deallocate the memory allocated for the array.
  • arr = NULL;: Set the pointer to NULL to avoid dangling pointers, which can lead to undefined behavior if dereferenced.

Best Practices and Common Mistakes

  • Always check for NULL: After using malloc, calloc, or realloc, check if the returned pointer is NULL to avoid dereferencing a null pointer.
  • Free memory: Always free the dynamically allocated memory using free to prevent memory leaks.
  • Set pointers to NULL after freeing: This prevents accidental usage of freed memory, which can cause crashes.
  • Use sizeof: When allocating memory, always use sizeof(type) to ensure the correct amount of memory is allocated.

Conclusion

Dynamic memory allocation is a powerful concept in C that allows for flexible memory management. By mastering the use of malloc, calloc, realloc, and free, you can create more efficient and responsive applications. Remember to always check for successful memory allocation, free allocated memory when it is no longer needed, and set pointers to NULL after freeing to avoid potential issues.

S
Shubham Saini
Programming author at Code2Night — sharing tutorials on ASP.NET, C#, and more.
View all posts →

Related Articles

Mastering Linked Lists in C: A Comprehensive Guide
Mar 14, 2026
Mastering Arrays in C: Types and Examples Explained
Dec 09, 2023
Mastering 2-D Arrays in C: A Complete Guide with Examples
Sep 25, 2023
Understanding CWE-416: Use After Free Vulnerabilities in Memory Safety
Mar 24, 2026
Previous in C
Understanding Pointers in C Programming: A Comprehensive Guide
Next in C
Understanding Structures in C Programming: A Comprehensive Guide
Buy me a pizza

Comments

🔥 Trending This Month

  • 1
    HTTP Error 500.32 Failed to load ASP NET Core runtime 6,939 views
  • 2
    Error-An error occurred while processing your request in .… 11,281 views
  • 3
    Comprehensive Guide to Error Handling in Express.js 236 views
  • 4
    ConfigurationBuilder does not contain a definition for Set… 19,464 views
  • 5
    Complete Guide to Creating a Registration Form in HTML/CSS 4,218 views
  • 6
    Mastering Unconditional Statements in C: A Complete Guide … 21,507 views
  • 7
    Mastering JavaScript Error Handling with Try, Catch, and F… 162 views

On this page

More in C

  • Mastering Unconditional Statements in C: A Complete Guide wi… 21507 views
  • Understanding C: A Complete Guide with Examples 5147 views
  • Mastering Unconditional Statements in C: A Complete Guide wi… 4219 views
  • Introduction to C: A Step-by-Step Guide with Examples 3587 views
  • Check if the character is a vowel or a consonant. 3541 views
View all C posts →

Tags

AspNet C# programming AspNet MVC c programming AspNet Core C software development tutorial MVC memory management Paypal coding coding best practices data structures programming tutorial tutorials object oriented programming Slick Slider StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1770
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blog Archive
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
  • SEO Analyzer
Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • SQL Formatter
  • Diff Checker
  • Regex Tester
  • Markdown to HTML
  • Word Counter
More Tools
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Base64 Encoder
  • JWT Decoder
  • UUID Generator
  • Image Converter
  • PNG to ICO
  • SEO Analyzer
By Language
  • Angular
  • Angular js
  • ASP.NET
  • Asp.net Core
  • ASP.NET Core, C#
  • ASP.NET MVC
  • ASP.NET Web Forms
  • C
  • C#
  • C#, ASP.NET Core, Dapper
  • C#, ASP.NET Core, Dapper, Entity Framework
  • DotNet
  • General Web Development
  • HTML, CSS
  • HTML/CSS
  • Java
  • JavaScript
  • JavaScript, HTML, CSS
  • JavaScript, Node.js
  • Node.js
  • Python
  • Python 3.11, Pandas, SQL
  • Python 3.11, SQL
  • Python 3.11, SQLAlchemy
  • Python 3.11, SQLAlchemy, SQL
  • Python 3.11, SQLite
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ·  Terms
Translate Page
We use cookies to improve your experience and analyze site traffic. By clicking Accept, you consent to our use of cookies. Privacy Policy
Accessibility
Text size
High contrast
Grayscale
Dyslexia font
Highlight links
Pause animations
Large cursor