×

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

C Program to Find the Largest Number using Ternary Operator

In this tutorial, we will write some program to determine which of the provided integers is larger using the ternary operator, also known as the conditional operator in C. Ternary Operator: The ternary...

3 minutes read.

Types of Pointers in C

Pointers in C A pointer is a variable and this variable contains the address of another variable, i.e it’s a variable which has the address of another variable as its value....

4 minutes read.

Flow Chart of For loop in C

This is a flowchart that represents the process of executing the for loop in the C programming language. Generally, as we know there are three main components of for loop:1. The...

3 minutes read.

Find Day from Day in C Without using function

Introduction: In the given article, I find daily in C without using functions. It takes 365 days for the earth to revolve around the sun. It will be close to...

3 minutes read.

Sizeof in C

A pointer in C is defined as a variable that stores the information of the address of another variable. A pointer can be incremented or decremented, which means we can...

4 minutes read.

One Dimensional Array in C

One Dimensional Array in C: In the C programming language, an array is defined as a collection of one or more values of the same type. Every value present in...

4 minutes read.

Explain the Increment and Decrement Operators in C

In the C programming language, the increment operator (++) and the decrement operator (--) are used to increase or decreasing a variable’s value by 1, respectively. The increment operator is written...

10 minutes read.

Assert() Function in C

Assert (): In C, the statements are executed with the exit statement. In C language declare, and it tests the condition parameters. If the statement executed will be false, it...

3 minutes read.

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...

3 minutes read.

DSA Program in C

How is a Data Structure Implemented? The foundational terms of a data structure are the following terms. Data may be arranged using data structures to make it easier to use. Each data...

20 minutes read.

Array Of Structures in C

The C programming language allows us to store multiple elements of the same type in arrays. We can use strings to store multiple elements of a character data type. Still,...

4 minutes read.

Difference between while and for loop in C

While Loop The syntax that can be used for the ‘while’ loop in the C programming language is mentioned below: while (test expression or termination condition)  {   // the main body of the...

6 minutes read.

Simple Programs in C Language

In this article, we will discuss the basic programs in C language. Addition of two values in C. Swapping two values. Finding the odd or even values. Finding vowels and consonants in C. Finding the...

11 minutes read.

C pre-processor

The C processor is a macro processor which is used to compile the source code of the program (step by step) . It is not a part of the compiler....

4 minutes read.

C program to compare the two strings

C program to compare the two strings Strings can be compared either by using the string function or without using string function. First, we will look at how we can compare the strings with...

4 minutes read.

abs() function in C

abs() function is a built-in function present in the stdlib.h header file. It returns an integer value. abs() function converts a negative value into a positive value. For example, if...

4 minutes read.

Use of free() function in C

Introduction The free() function uses in C programming language. The free() function in the C programming language uses to release or deallocate the memory blocks; these blocks are previously allocated by calloc(), malloc() or realloc()...

3 minutes read.

Functions in C

What is function? Functions are defined as the set of announcements which take inputs, perform operations and provide results. The operation of a function only performs when the function gets called....

4 minutes read.

C program to Store Information of Students Using Structure

What is the Structure in C? User-defined data types include structures. Structures aid your ability to combine things of various categories into a single group. Like arrays, it operates similarly. A...

3 minutes read.

Do WHILE LOOP in C Programming Examples

Before understanding the programming examples of the Do-While loop, we have to know what is Do-While loop in C. So, let's start with the definition of the Do-While loop. What is...

5 minutes read.