×

Advantages of Dynamic Memory Allocation in C

Dynamic Memory Allocation

Dynamic memory allocation is a process of assigning or allocating memory to a variable during the execution of a program. Dynamic memory allocation provides storage according to the user's need and also helps to reduce the wastage of memory.

Different ways to allocate memory dynamically:

  1. Malloc() – this function allocates a block of memory and returns a pointer to the first byte of the allocated space.
  2. Calloc() – this function allocates memory for n number of elements and returns a pointer to the memory
  3. Realloc() – this function allocates new memory for previously allocated memory.
  4. Free() – this function free up space acquired by some pointer.

Malloc () function

Malloc allocates a block of memory and returns a pointer to the first byte of allocated memory. It returns NULL if requested memory cannot be allocated.

Syntax:

Ptr =  (data type *)malloc(size);

Example-

A = (int *)malloc(10 *sizeof(int));

In this, a memory block of 10 * 4(size of integer) will be allocated, and the pointer 'a' will point to the first byte of allocated memory.

Code example:

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int i, n, *p;
    printf("Enter number of elements: ");
    scanf("%d", &n);
    p=(int*)malloc(n * sizeof(int));  //memory allocated using malloc
    if(p == NULL)   {
             printf("memory cannot be allocated\n");
     }
    else {
              printf("Enter elements in array:\n");
     	  for(i=0; i<n; i++)  {
               scanf("%d",&*(p+i));
          }
    printf("Elements of array are\n");
    for(i=0; i<n; i++) {
        printf("%d ",*(p+i));
      }
    return 0;
	}
}

OUTPUT

Advantages of Dynamic Memory Allocation

Calloc () function

The callocfunction allocates more than one memory block, each of the same size. It is the same as the malloc function, but the only difference is it takes two arguments: the number of elements and size.

Syntax-

ptr = (data type *)calloc(elements, size);

Example-

x =( int *)calloc(10, sizeof(int));

In this, 10 blocks of memory are allocated of the size of integer 'x'

 pointer will point at the first block of memory.

Code example:

#include <stdio.h>
#include <stdlib.h>
int main() {
    int count, i, *ptr;
    printf("Enter number of elements: ");
    scanf("%d", &count);


    ptr = (int*) calloc(count, sizeof(int));
    if(ptr == NULL)
    {
        printf("Error! memory not allocated.");
        exit(0);
    }
     printf("Enter elements: ");
    for(i = 0; i < count; i++)   {
        scanf("%d", ptr + i);
	}
     return 0;
}

OUTPUT

Advantages of Dynamic Memory Allocation

Free () function

Free function frees up the space/ memory allocated previously by calloc or malloc.

Syntax-

 Free(ptr);

Example-

Free(x);

Code example:

#include <stdio.h>
#include <stdlib.h>
int main() {
	int* ptr, n;
	printf("Enter number of Elements: ");
	scanf("%d", &n);
	ptr = (int*)malloc(n * sizeof(int));
	if (ptr == NULL) {
		printf("Memory not allocated \n");
		exit(0);
	}
	free(ptr);
printf("Successfully freed memory using free function.");
return 0;
}

OUTPUT

Advantages of Dynamic Memory Allocation

Realloc () function

The realloc function is used to alter the size of memory allocated previously. It is helpful if a user needs more memory during the execution of a program.

Syntax-

realloc(pointer, size);

Example-

x =( int *)calloc(10, sizeof(int));
x= (int *)realloc(x, 100);

In this, the realloc function increases the memory for 'x' pointer to 100 bytes.

Code example:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
  int main () {
  char *str;
  str = (char *) malloc(15);
  strcpy(str, "burger");
  printf("String = %s,  Address = %u\n", str, str);
  /* Reallocating memory */
  str = (char *) realloc(str, 25);
  strcat(str, ".com");
  printf("\nString = %s,  Address = %u\n", str, str);
  free(str);
   return(0);
}

OUTPUT

Advantages of Dynamic Memory Allocation

Advantages of dynamic memory allocation

  1. Allocation of memory
    In static memory allocation, space is provided at compile time, resulting in much memory waste. But in dynamic memory allocation, memory is assigned at run time so that the memory can be used accordingly with zero wastage of memory.
  2. Efficiency
    Dynamic memory allocation is more efficient than static memory and flexible.
  3. Reusability of memory
    The previously used memory can be used again using the free () function. This function frees the memory allocated before to use in the future.
  4. Memory Reallocation
    In static memory allocation, we cannot change the size of any data structure if memory is allocated. But in dynamic memory allocation, we can change the size at our convenience by using the realloc() function.
  5. Cost-effective
    Dynamic memory allocation is cost-effective as no extra cost is required for memory because memory is allocated per the user's needs.

Related Topics

Derived Data Types in C

A variable in a program occupies some space in the computer's memory where some value is stored. Each variable in C has an associated data type. A value to be...

4 minutes read.

Format Specifier in C

Format Specifier in C Format specifiers can be described as an operator that is used to print the data referred by any object or variable in combination with the printf ()...

3 minutes read.

Java Array vs ArrayList

As we all know, arrays are linear data structures that allow you to add elements to them continuously in memory address space, whereas ArrayList is a Collection framework class. Despite...

4 minutes read.

Volatile in C

Introduction A volatile keyword is a qualifier in C. Qualifiers are nothing but keywords which are used to modify the properties of a variable. Qualifiers are of two types: 1) Const The const type...

3 minutes read.

Variable Declaration in C

What is a Variable? A Variable is nothing more than a name for a memory place where data/information can be stored. Any alphabet (from a to z or A to Z), the...

4 minutes read.

Built-in functions in C

The function is a set of instructions and statements enclosed in the "{}" delimiter. In c, there are two types of functions. Pre-define functions/ Built-in functionsUser define function. Built-in functions in C:- These...

8 minutes read.

Difference between rand() and srand() function in C

What is the rand()? The rand() means random function. This function is used in C. It generates random numbers in the range of 0 to the RAND_MAX. Suppose we generate a...

3 minutes read.

Top Array Keywords in C

Sorting array in C Types of array in C Array of structure in C How do you initialize an array in C Array declaration in C Array of strings in C Multidimensional array in C Reverse array...

1 minute read.

Compound Interest Program in C

Interest on loans and deposits is compound interest. This is the most commonly used concept in everyday life. Compound interest on an amount is based on principal and interest earned...

3 minutes read.

Factorial Program in C Using While Loop

Before looking into the mechanism of factorial program, first, you have to understand about the working of a while loop. While Loop The syntax that has been used for the “while” loop...

4 minutes read.

While Loop in C programming examples

Introduction There is always a header file containing all the essential data regarding inputs and outputs of various functions in the C programs. The following statement describes how to use/add header file...

22 minutes read.

Difference between If Else and Nested If Else in C

What is the If Else statement in C? In C programs, if else conditions are used to perform some operations based on specific conditions. The operation is only executed if the...

6 minutes read.

Evaluation of Arithmetic Expression in C

We can use the "eval" function in C to evaluate an arithmetic expression stored as a string. However, using "eval" is generally considered bad practice and can lead to security...

4 minutes read.

#error #pragma in C

#error, #pragma in C #error, also known as the error directive in the C language. It will not allow you to make any compilation fail and immediately issues a statement which...

4 minutes read.

Find the Largest Three Distinct Elements in an Array using C/C++

In this tutorial, we will demonstrate how to use a C/C++ programme to locate the highest three different elements in an array. C/C++ Program to Find the Largest Three Different Elements...

3 minutes read.

Tower of Hanoi in C

What is Tower of Hanoi? The Tower of Hanoi is a gaming problem that was created in 1883 by a French mathematician named Édouard Lucas. The Tower of Hanoi temple in...

4 minutes read.

Variable in C

Variable is an identifier that holds data in memory. It is used to identify input data in a program. The value of the variable can change at the time of...

2 minutes read.

Loop Statement in C

Loop statement is used to execute one or more statement repeatedly multiple times. There are three types of loops in C language. Why use loop? We can use loop because it executes a...

2 minutes read.

Limitations of Synchronisation and Uses of Static Synchronisation in Multithreading

The multithreading component of java is the element around which the idea rotates as it permits simultaneous execution of at least two program pieces for the most significant usage of...

9 minutes read.

How to find square root in C Language

Before understanding the square root program in C language, one must know about the square root of a number. A square root is a mathematical term. The square root of a...

5 minutes read.