C program that demonstrates dynamic memory allocation

      Dynamic memory allocation in C programming is possible with help of special library functions available in “stdlib.h”. Those are malloc(), calloc() and realloc(). This program allocates the memory using calloc() function and computes the sum of allocated variables.

dynamic memory allocation program in c



Source Code :

#include<stdio.h>
#include<stdlib.h>
int main()
{
	int N,*a,i,s=0;
	printf("\n Enter the number of elements of the array :");
	scanf("%d",&N);                   //Step 1
	a=(int *)calloc(N,sizeof(int));   //Step 2
	if(a==NULL)
	{
		printf("\n Memory allocation unsuccessful...");
		exit(0);
	}
	printf("\n Enter the array elements one by one :");
	for(i=0; i < N;++i)   
	{
		scanf("%d",(a+i));      //Step3
		s+=a[i];
	}
	printf("\n Sum is %d ",s);      //Step4
	return 0;
}

void * calloc(size_t count, size_t eltsize)  //Step2
{
	size_t size = count * eltsize;
	void *value = malloc(size);
	if(value != 0)
	memset(value, 0, size);
	return value;
}


edit-code-image

Sample Test cases:

1.  Enter the number of elements of the array:5
    Enter the array elements one by one:  1
                                          2
                                          3
                                          4
                                          5
                                Sum is 15

2.  Enter the number of elements of the array: -1
    Memory allocation unsuccessful...

3.  Enter the number of elements of the array:3
    Enter the array elements one by one : 89
                                          345
                                          12345
                                   Sum is 12779

Explanation:

Step 1: Program reads the number of elements from the user using scanf() function.

Step 2: The memory for the elements is allocated using calloc() function. The calloc() function is again defined by the user which uses malloc() and memset() functions implicitly.

Step 3: The values of an array are read from the user using scanf() function.

Step 4: The computed sum of elements of an array is printed on the output screen using printf() function.

More Insights:

1. More about DMA.