Programming with C

⌘K
  1. Home
  2. Docs
  3. Programming with C
  4. Structures
  5. Dynamic Memory Allocation

Dynamic Memory Allocation

The process of allocating memory at run time is known as dynamic memory allocation. C does not inherently have this facility, there are four library routines known as memory management functions that can be used for allocating and freeing memory during program execution.

These functions are,

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

These functions are present in header file alloc.h or in stdlib.h

malloc

  • Allocates requested number of bytes and returns a pointer to the first byte of the allocated space
  • A block of memory can be allocated using the function malloc
  • Reserves a block of memory of specified size and returns a pointer of type void
  • The return pointer can be type-casted to any pointer type

General format:

type *p;
p =  (type *) malloc (byte_size);

Example

 p = (int *) malloc(100 * sizeof(int));

Example Code

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

int main()
{

	// This pointer will hold the
	// base address of the block created
	int* ptr;
	int n, i;

	// Get the number of elements for the array
	printf("Enter n");
	scanf("%d",&n);
	printf("Enter number of elements: %d\n", n);

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

	// Check if the memory has been successfully
	// allocated by malloc or not
	if (ptr == NULL) {
		printf("Memory not allocated.\n");
		exit(0);
	}
	else {

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

		// Get the elements of the array
		for (i = 0; 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]);
		}
	}

	return 0;
}

Output

C:\TDM-GCC-64>gcc 4_malloc.c
C:\TDM-GCC-64>a
Enter n 5
Enter number of elements: 5
Memory successfully allocated using malloc.
The elements of the array are: 1, 2, 3, 4, 5,

calloc

Allocates space for an array of elements, initializes them to zero and then returns a pointer to the memory.

Syntax

type *p = calloc(num, sizeof(type));
int* ptr_to_array = calloc(4, sizeof(type));

Example

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

int main()
{

	// This pointer will hold the
	// base address of the block created
	int* ptr;
	int n, i;
	float sum=0;

	// Get the number of elements for the array
	printf("Enter n:");
	scanf("%d",&n);

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

	// Check if the memory has been successfully
	// allocated by calloc or not
	if (ptr == NULL) {
		printf("Memory not allocated.\n");
		exit(0);
	}
	else {

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

		// Get the elements of the array
		for (i = 0; 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]);
		}
		// sum the elements
		for(i=0;i<n;i++)
		{
			sum = sum +ptr[i];
		}
		printf("Sum = %f",sum);
	}

	return 0;
}

Output

C:\TDM-GCC-64>gcc 4_calloc.c
C:\TDM-GCC-64>a
Enter n:5
Memory successfully allocated using calloc.
The elements of the array are: 1, 2, 3, 4, 5, Sum = 15.000000

realloc

  • “realloc” or “re-allocation” method in C is used to dynamically change the memory allocation of a previously allocated memory.
  •  In other words, if the memory previously allocated with the help of malloc or calloc is insufficient, realloc can be used to dynamically re-allocate memory.
  •  re-allocation of memory maintains the already present value and new blocks will be initialized with default garbage value.

Syntax

ptr = realloc(ptr, newSize); 

where ptr is reallocated with new size ‘newSize’.

Example

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

int main()
{

	// This pointer will hold the
	// base address of the block created
	int* ptr;
	int n, i;

	// Get the number of elements for the array
	n = 5;
	printf("Enter number of elements: %d\n", n);

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

	// Check if the memory has been successfully
	// allocated by malloc or not
	if (ptr == NULL) {
		printf("Memory not allocated.\n");
		exit(0);
	}
	else {

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

		// Get the elements of the array
		for (i = 0; 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]);
		}

		// Get the new size for the array
		n = 10;
		printf("\n\nEnter the new 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 successfully 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

C:\TDM-GCC-64>gcc 4_realloc.c
C:\TDM-GCC-64>a
Enter number of elements: 5
Memory successfully allocated using calloc.
The elements of the array are: 1, 2, 3, 4, 5,

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

free

  • “free” method in C is used to dynamically de-allocate the memory.
  • The memory allocated using functions malloc() and calloc() is not de-allocated on their own.
  • Hence the free() method is used, whenever the dynamic memory allocation takes place. It helps to reduce wastage of memory by freeing it.

Syntax

free(ptr)

Example

#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;

	// Get the number of elements for the array
	n = 5;
	printf("Enter number of elements: %d\n", n);

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

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

	// 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 the memory
		free(ptr);
		printf("Malloc Memory successfully freed.\n");

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

		// Free the memory
		free(ptr1);
		printf("Calloc Memory successfully freed.\n");
	}

	return 0;
}

Output

Enter number of elements: 5
Memory successfully allocated using malloc.
Malloc Memory successfully freed.

Memory successfully allocated using calloc.
Calloc Memory successfully freed.

Difference between calloc and malloc

Views: 0

How can we help?

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments