C Dynamic Memory Allocation

C Dynamic Memory Allocation

C Dynamic Memory Allocation
In this chapter you will learn to dynamically allocate memory in your program using the standard library functions malloc(), calloc(), free() and realloc().

In C programming, the size of an array is unknown until compile time. That is, until the compiler converts your code into a language that the computer understands. So sometimes the size of the array may be less or more than required.

Dynamic memory allocation either holds more memory while your program is running or releases it when it is not needed.

In simple terms, dynamic memory allocation allows you to manually manage your program’s memory space.

Although there is no dynamic technique for inheriting memory allocation in C program, there are "stdlib.h" library functions for dynamic memory allocation under header file.

Function Use of functions
malloc() Allocates memory space upon request and returns a pointer to the first byte of allocated memory.
calloc() Allocates memory space for array elements and has an initial value of 0 (zero). Then returns a pointer to memory.
free() Frees/frees previously allocated memory space.
realloc() Changes previously allocated memory space.

C malloc() function

malloc stands for “memory allocation”.

malloc()The function occupies a specific block of memory and returns a pointervoid of type from which any pointer can be cast.

Syntax of malloc()

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

				
			

Here ptr is a cast type pointer. malloc()The function returns a pointer into memory of the specified size in bytes. Returns NULL pointer if memory space is not enough.

				
					ptr = (int*) malloc(50 * sizeof(int));

				
			

This statement intcan allocate 100 or 200 bytes of memory depending on its size (2 or 4 bytes), respectively, and the pointer refers to the address of the first byte of memory.

C calloc() function

The full form of calloc is “contiguous allocation”.

The only difference between malloc() and calloc() is that the malloc() function allocates a single block of memory whereas the calloc() function allocates multiple blocks of memory and the size of each is set to 0( zero).

Syntax of calloc()

				
					ptr = (cast-type*)calloc(n, element-size);

				
			

This statement will allocate contiguous memory space for an array with n number of elements. For example:

				
					ptr = (float*) calloc(50, sizeof(double));

				
			

This statement will allocate double (8 bytes) contiguous memory space for the 50 element array.

C free() function

Memory dynamically allocated by the calloc() or malloc() function cannot be automatically freed. So you must use the free() function to release the allocated memory.

free() syntax

				
					free(ptr);

				
			

This statement frees the space allocated in memory by the pointer(ptr).

Example: Use of C malloc() and free() functions

Write a C program to find the sum of n number of elements given the input by the user.

Executing this program requires dynamically allocating memory using the malloc() function.

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

int main()
{
 int num, i, *ptr, sum = 0;

 printf("Enter number of elements: ");
 scanf("%d", &num);

 ptr = (int*) malloc(num * sizeof(int)); //Allocating memory using malloc
 if(ptr == NULL)
 {
 printf("Error! memory not allocated.");
 exit(0);
 }

 printf("Enter elements of array: ");
 for(i = 0; i < num; ++i)
 {
 scanf("%d", ptr + i);
 sum += *(ptr + i);
 }

 printf("Sum = %d", sum);
 free(ptr);
 return 0;
}
				
			

Example: Use of C calloc() and free() functions

Write a C program to find the sum of n number of elements given the input by the user.

Executing this program requires dynamically allocating memory using the calloc() function.

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

int main()
{
 int num, i, *ptr, sum = 0;

 printf("Enter number of elements: ");
 scanf("%d", &num);

 ptr = (int*) malloc(num * sizeof(int)); //Allocating memory using malloc
 if(ptr == NULL)
 {
 printf("Error! memory not allocated.");
 exit(0);
 }

 printf("Enter elements of array: ");
 for(i = 0; i < num; ++i)
 {
 scanf("%d", ptr + i);
 sum += *(ptr + i);
 }

 printf("Sum = %d", sum);
 free(ptr);
 return 0;
}
				
			

C realloc() function

If the size of the already allocated memory is less or more than required, you can change the size of the previous memory using the realloc() function.

Syntax of realloc()

				
					ptr = realloc(ptr, newsize);

				
			

Here ptr is the new size allocated memory.

Example: Using the C realloc() function

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

int main()
{
    int *ptr, i , n1, n2;
    printf("Enter size of array: ");
    scanf("%d", &n1);

    ptr = (int*) malloc(n1 * sizeof(int));

    printf("Address of previously allocated memory: ");
    for(i = 0; i < n1; ++i)
         printf("%u\t",ptr + i);

    printf("\nEnter new size of array: ");
    scanf("%d", &n2);
    ptr = realloc(ptr, n2);
    for(i = 0; i < n2; ++i)
         printf("%u\t", ptr + i);
    return 0;
}
				
			

Leave a Comment

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