Youtube RSS Feed
Learn with Vikas Suhag
Dynamic memory allocation and deallocation in C Language using free() function
Mar 06, 2022   Vikas Suhag

#include <stdio.h>
#include <stdlib.h>
int main()
{
    // This pointer will hold the base address of the block created
    int *ptr, *ptr1;
    int n, i;
    
    n = 5; // Get the number of elements for the array
    printf("Enter number of elements: %d\n", n);

    ptr = (int*)malloc(n * sizeof(int));     // Dynamically allocate memory using malloc()
    
    ptr1 = (int*)calloc(n, sizeof(int));     // Dynamically allocate memory using calloc()

    // Check if the memory has been successfully //allocated by malloc or not
    if (ptr == NULL || ptr1 == NULL)
    {
        printf("Memory not allocated.\n");
        exit(0);
    }
    else
    {
        // Memory has been successfully allocated
        printf("Memory successfully allocated using malloc.\n");
        free(ptr); // Free the memory
        printf("Malloc Memory successfully freed.\n");
        // Memory has been successfully allocated
        printf("\nMemory successfully allocated using calloc.\n");
        free(ptr1); // Free the memory
        printf("Calloc Memory successfully freed.\n");
    }
    return 0;
}

 


Leave a Comment

* Email will not be published.
All comments are only visible after approval.
Most Viewed articles
Search
Subscribe to Email Updates
Vikas Suhag

I am Engineer, Developer, Teacher, Blogger, Vlogger, Traveller, Photographer...

I have been developing websites, writing blogs and recording videos during my travel while being a full tim ...

Youtube Channel
Podcast
Subscribe to Email Updates
Connect With Us
Youtube RSS Feed
© 2022 Learn with Vikas Suhag. All Rights Reserved.