Dynamic Memory Allocation In C

Dynamic Memory Allocation In C

Introduction

Memory allocation can be defined as the process of allocating portions of memory inside programs. This is done so that memory can be used for storing variables or instances of classes and structures. For example, when variables are declared, the operating system allocates blocks of memory for them that can be accessed by declaring the respective objects.

C interacts with memory automatically, statically, or dynamically and manages memory through functions such as realloc() or malloc(). Dynamic Memory Allocation in C++ utilizes these functions as well, however, new and delete operators provide similar functionalities thus making it simpler.

Even then, there are situations where these operators don’t work and one might need to use malloc(). C programmers, however, must always rely on automatic, static, or dynamic memory allocation. Among those three, dynamic memory allocation is always more flexible and efficient.

Let us learn how to use dynamic memory allocation and understand why manual memory management is important in C.

What is Dynamic Memory Allocation in C?

Fundamentally, Dynamic Memory Allocation in C refers to manual memory management through 4 functions in C standard library. In C, Dynamic Memory Allocation can simply be defined as a process of changing the size of data structures such as arrays during runtime.

This allows allocation of memory at runtime instead of during compilation as seen during static memory allocation in C. Static data exists for the lifetime of the program whether it is needed or not. Using dynamic memory allocation allows programmers much more flexibility in terms of managing allocated memory.

Even in the case of automatically-allocated data, it is unable to be functional during multiple function calls. Thus, only dynamic memory allocation can be used across multiple situations due to allocating memory from the heap or the free memory which is a segment of memory especially structured for these functions.

Library functions (from the  <stdlib.h> header file) such as malloc() can be used for manually allocating blocks of memory from the heap while the programs access these blocks through pointers that malloc() returns. When the memory is not needed or being used, it is simply deallocated so that it can be used for other purposes.

C is a structured programming language and thus has certain rules and limitations for memory management. For instance, the rules for changing array sizes. In order to truly understand dynamic memory allocation, we must first understand what an array truly is.

Arrays can basically be described as collections of objects stored in sequential memory locations. Let’s take an example where the length of an array is 6 but only 3 elements need to be entered into the array. Fundamentally, the remaining indices are a waste of memory in this situation.

Arrays are distributed equally and thus half of the array is being wasted and this problem is encountered many times when allocating memory during compilation. This kind of problem can also be seen when there are fewer indices than the elements that need to be entered.

For instance, suppose the length of an array is 5 but 6 more elements need to be entered, thus requiring 11 indices. In these kinds of situations, where the size of the array needs to be altered, dynamic memory allocation is used.

There are four library functions in C that facilitate this kind of manual memory management. These four include the following:

  • malloc()
  • free()
  • calloc()
  • realloc()

calloc() and free() existed from the original standard library in C followed by malloc(). realloc() was later introduced as a low-level memory allocation function. These functions were designed as code that allows management of storage in Unix and Unix-like systems by requesting memory from the OS.

Let’s delve deeper into what these functions are and how they can be used.

Dynamic Memory Allocation using malloc()

‘Malloc’ refers to basic memory allocation in C and the malloc() function is used for dynamically allocating single large blocks of memory with a specific size. This function returns pointers that are of the void type.

This allows them to be altered and cast into pointers of any value or form and thus initializes all the blocks with default garbage values initially. If space in the storage is insufficient, the allocation process will fail and return a NULL pointer.

Here is the syntax: 

ptr=(cast-type*)malloc(byte-size)  

The size of the cast-type or int(in the example below) determines the byte size of the allocated memory and ptr, the pointer stores the addresses of the first bytes in the allocated memory. 

Here is an example of using malloc() in C:

#include<stdio.h>  
#include<stdlib.h>  
int main(){  
  int n,i,*ptr,sum=0;    
    printf("How many elements will be there? ");    
    scanf("%d",&n);    
    ptr=(int*)malloc(n*sizeof(int));  //memory allocated using malloc    
    if(ptr==NULL)                         
    {    
        printf("Memory allocation failed.");    
        exit(0);    
    }    
    printf("Enter the elements: ");    
    for(i=0;i<n;++i)    
    {    
        scanf("%d",ptr+i);    
        sum+=*(ptr+i);    
    }    
    printf("Total=%d",sum);    
    free(ptr);     
return 0;  
} 

This will be the Output:

How many elements will be there? 10
Enter the elements: 5
5
5
5
5
5
5
5
5
5
Total=50

Dynamic Memory Allocation using calloc()

‘Calloc’ stands for ‘contiguous allocation’ and calloc() is used for dynamically allocating multiple blocks of memory as specified. This method is similar to using malloc() but calloc() initialised each block with the default of 0 as compared to void. The calloc() method also has two arguments or parameters. 

Here is the syntax:
ptr = (cast-type*)calloc(n, element-size);

The number of elements is determined by n and element size establishes the size of each element.

Here is an example of using calloc() in C:

#include<stdio.h>  
#include<stdlib.h>  
int main(){  
 int n,i,*ptr,sum=0;    
    printf("How many elements will be there? ");    
    scanf("%d",&n);    
    ptr=(int*)calloc(n,sizeof(int));  //memory allocated using calloc    
    if(ptr==NULL)                         
    {    
        printf("Memory allocation failed.");    
        exit(0);    
    }    
    printf("Enter the elements: ");    
    for(i=0;i<n;++i)    
    {    
        scanf("%d",ptr+i);    
        sum+=*(ptr+i);    
    }    
    printf("Total=%d",sum);    
    free(ptr);    
return 0;  
}    

This will be the Output:

How many elements will be there? 2
Enter the elements: 2
3
Total=5

Dynamic Memory Allocation using free()

The free() function is used for dynamically deallocating the memory using malloc() and calloc(). Only using free() is insufficient for deallocation and thus uses these other functions from the library. This function is fundamentally used for freeing memory and in turn reducing the amount of memory being wasted.

Here is the syntax:
free(ptr)

Here is an example of using free() in C:

#include <stdio.h>
int main() {
int* ptr = malloc(20 * sizeof(*ptr));
if (ptr != NULL){
  *(ptr + 2) = 40;
  printf("The second integer’s value is %d",*(ptr + 2));
}
free(ptr);
}

This will be the Output:

The second integer’s value is 40

Dynamic Memory Allocation using realloc()

‘Realloc’ stands for re-allocation and is used for dynamically altering or changing the memory allocation of a commissioned allocated memory. So simply put, realloc() is used for memory reallocation when prior memory allocation using calloc() or malloc() is insufficient.

realloc() allows memory to maintain the pre-given values and new blocks of memory to be initialised with garbage values. Similarly, if the space in memory is insufficient, the allocation processes will fail and return NULL pointers.

Here is the syntax:
ptr = realloc(ptr, newSize)

Here, ptr is reallocated with newSize to the required new size. In the example below the size 50 will be reallocated to the new size of 75.

Here is an example of using realloc() in C: 

#include <stdio.h>
#include <stdlib.h>
    int main() {
        int i, * ptr, sum = 0;
        ptr = malloc(50);
        if (ptr == NULL) {
            printf("Memory allocation failed.");
            exit(0);
        }
        
        ptr = realloc(ptr,75);
    if(ptr != NULL)
           printf("Memory reallocation is successful.\n");
           
    return 0;

    }

This will be the Output:

Memory reallocation is successful.

Frequently Asked Questions

What is dynamic memory allocation with an example?

Dynamic memory allocation is the manipulation of memory or array sizes during runtime. An example of dynamic memory allocation would be changing an array with the size of 10 to a new size of 20.

What is the use of dynamic memory allocation in C?

It is used for memory management in C. For example, one can reduce array sizes to remove the indices that are being wasted or increase the array size to fit in more elements.

What is dynamically memory allocation?

Manually manipulating the blocks of memory during runtime is referred to as dynamically allocating memory.

What does malloc () calloc () realloc () free () do?

malloc() manipulates a single block of memory while calloc() manipulates a specific number of memory blocks. realloc() is used for reallocating already allocated memory while free() simply frees memory by removing excess indices.

What is the function of malloc?

malloc() is used for initialising blocks of memory with void values so that they can be cast into any value or form.

What does malloc stand for?

‘Malloc’ stands for memory allocation and malloc() is a simple memory allocation function.

How to learn more about Dynamic memory allocation in C with programming examples?

Budding programmers should download research and study material related to dynamic memory allocation in c pdf files from reputed universities and institutes. You can also search up dynamic memory allocation in c by Naresh technologies to get an understanding of dynamic memory allocation in c in Hindi.

Is dynamic memory allocation in C++ possible?

Yes, it is possible, however, programmers have the option of using new and delete operators for fulfilling the same functions.

Why is dynamic memory allocation better than static memory allocation?

Statically allocated data exists for the entire duration of the program’s lifetime, thus offering less in terms of flexibility while increasing the waste of memory.

Key Takeaways

Dynamic memory allocation of structures in c is an important topic and must be understood extensively in order to advance as a C language programmer. Unlike other methods such as static memory allocation and automatic memory allocation, dynamic memory allocation is more flexible and reliable for program lifetimes(compared to automatically allocated data).

Thus, offering the ability to manipulate memory allocation at any given time. In this method, the allocation is carried out during runtime instead of during compilation, thus making it a great idea to manually manage memory using dynamic memory allocation.

Exit mobile version