Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Dynamic Memory Allocation in C

Last Updated on March 2, 2023 by Prepbytes

In this article, we will study about that how memory allocation takes place in c dynamically
Function which are used for dynamic allocation like malloc(),calloc(),realloc(), free(), differences
between Static Memory Allocation and Dynamic Memory Allocation.

Dynamic Memory Allocation in C Langauge

In C, dynamic memory allocation refers to the process of allocating memory at runtime. So as result, this allows for the creation of data structures of variable sizes, such as arrays, linked lists, and trees. In simple words, memory can be allocated after the
program begins execution. Dynamic memory allocation in c is allocated from the heap using some standard library functions like malloc(),calloc(),realloc(), and free() which are present in <stdlib.h>header

Difference between Static Memory Allocation and Dynamic Memory Allocation

  Dynamic Memory Allocation     StaticMemory Allocation
Memory is reserved at run time and we can allocate and deallocate Memory is reserved at compile time and we cannot allocate and deallocate
It uses heap space It uses stack space
It is more efficient and provides reusability of memory during run time It is less efficient and not provide reusability of memory

C malloc()

In C, malloc is a function which is in <stdlib.h> header file that is used to dynamically allocate memory at runtime. It takes a single argument, which is the number of bytes to allocate, and returns a pointer to the beginning of the allocated memory. The memory allocated by malloc is not initialized, so it contains garbage values. So it is the responsibility to initialize the memory before using it.

Note: If space is insufficient, allocation fails and returns a NULL pointer.

Syntax of Malloc():

ptr = (castType*) malloc(size)

Example of Malloc()

C calloc()

The C library function calloc() is used to allocate memory for an array of elements of a certain data type and initializes all bits to zero. The function takes two arguments: the number of elements in the array and the size of each element. It returns a pointer to the first byte of the allocated memory, or NULL if the request for memory could not be fulfilled.

Note: If space is insufficient, allocation fails and returns a NULL pointer.

Syntax of Calloc():

ptr = (castType*)calloc(n, size);

here, ‘size’ is the size of each element, and ‘n ‘is the no. of elements.

Example of Calloc()

C free()

The free() function in the C programming language is used to deallocate memory that has already been allocated using the malloc(), calloc(), or realloc() functions. Releasing the memory block indicated to by the address provided to it, it makes more allocations possible. To stop memory leaks in your program, you must utilize free() on dynamically allocated memory.

Syntax of Free() in C:

free(ptr);

Example of free()

C realloc()

By the word we understand “realloc” which means re-allocation in C programming, the realloc() function is used to change the size of a previously allocated memory block. It takes two arguments: a pointer to the memory block that you want to resize and the new size of the memory block. If the new size is larger than the original size, the function may move the memory block to a new location in order to accommodate the increased size. If the new size is smaller than the original size, the function will truncate the memory block to the new size. The syntax for the realloc() function is as follows:

Syntax of realloc()

ptr = realloc(ptr, newSize);

where ptr is reallocated with new size ‘newSize’.

Example of realloc() in C

Note: If space is insufficient, allocation fails and returns a NULL pointer.

Code Implementation:

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

int main()
{


    
    int* ptr,ptr1;
    int n, i;


    n = 7;
    printf(" number of elements are here is : %d\n", n);

    // Dynamically allocate memory using calloc()
    ptr = (int*)calloc(n, sizeof(int));
     ptr1 = (int*)malloc(n * sizeof(int));
     // dynamically allocate memory using malloc() which is not contagious 
     

    
    //  checking that allocated by malloc or not
    if (ptr == NULL) {
        printf("Memory not allocated.\n");
        exit(0);
    }
    else {

        // Memory has been successfully allocated
        printf(" Successfully allocated using calloc.\n");

        // Get the elements of the array
        for (i = 0; i < n; ++i) {
            ptr[i] = i + 1;
        }

        // here we  Printing the elements of the array
        printf("The elements of the array are: ");
        for (i = 0; i < n; ++i) {
            printf("%d, ", ptr[i]);
        }

        // Get the new size for the array
        n = 12;
        printf("\n\nnew size of the array: %d\n", n);

        // Dynamically re-allocate memory using realloc()
        ptr = realloc(ptr, n * sizeof(int));

        // Memory has been successfully allocated
        printf("Memory  re-allocated using realloc.\n");

        // Get the new elements of the array
        for (i = 5; i < n; ++i) {
            ptr[i] = i + 1;
        }

        // Print the elements of the array
        printf("The elements of the array are: ");
        for (i = 0; i < n; ++i) {
            printf("%d, ", ptr[i]);
        }

        free(ptr);
    }

    return 0;
}

Output:

number of elements are here is : 7
 Successfully allocated using calloc.
The elements of the array are: 1, 2, 3, 4, 5, 6, 7

new size of the array: 12
Memory  re-allocated using realloc.
The elements of the array are: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12

Explanation:
In the above C program we create two pointer variables ptr and ptr1. Pointer ptr is of dynamically allocated memory using calloc() whose size is 7 and then we use realloc() function to increase the size from 7 to 12. ptr1 is of allocated memory which forms by using malloc(this is not contagious). we first allocate the memory and then stored the value by applying for loop. After that, we increase the value of n by 7 to 12 so for increasing the size of the already allocated memory block we use the realloc() function. In last we use free() function which deallocates the ptr.

Summary
The process of allocating memory at runtime as opposed to compile-time is referred to as dynamic memory allocation in the C programming language. As a result, it is possible to create data structures of variable sizes, including trees, linked lists, and arrays. the malloc() and calloc are the two main C methods for allocating memory dynamically. the malloc() allocates a block of memory of a specified size, while calloc() allocates a block of memory for an array of elements, and realloc is used to change the size of a previously allocated memory and at last
free() this function is used to deallocate memory that has already been allocated using the malloc(), calloc(), or realloc() functions.

Leave a Reply

Your email address will not be published. Required fields are marked *