Write a C Program to understand dynamic memory allocation using malloc( ). Here’s a Simple Program to understand dynamic memory allocation using malloc( ) in C Programming Language.
The process of allocating memory during program execution is called dynamic memory allocation.
Library routines known as “memory management functions” are used for allocating and freeing memory during execution of a program. These functions are defined in stdlib.h.
MALLOC() FUNCTION IN C:
malloc () function is used to allocate space in memory during the execution of the program.
malloc () does not initialize the memory allocated during execution. It carries garbage value.
malloc () function returns null pointer if it couldn’t able to allocate requested amount of memory.
Syntax of malloc( ) function :
ptr = (cast-type *)malloc(byte-size) ;
Below is the source code for C Program to understand dynamic memory allocation using malloc( ) which is successfully compiled and run on Windows System to produce desired output as shown below :
SOURCE CODE : :
/* Program to understand dynamic memory allocation*/
#include<stdio.h>
#include<stdlib.h>
int main( )
{
int *p, n, i;
printf("Enter the number of integers to be entered : ");
scanf("%d", &n);
p = (int *)malloc(n * sizeof(int));
if(p==NULL)
{
printf("Memory not available\n");
exit(1);
}
for(i=0; i<n; i++)
{
printf("Enter an integer : ");
scanf("%d", p+i);
}
for(i=0; i<n; i++)
printf("%d\t", *(p+i));
return 0;
}
OUTPUT : :
//OUTPUT :
Enter the number of integers to be entered : 6
Enter an integer : 5
Enter an integer : 2
Enter an integer : 8
Enter an integer : 1
Enter an integer : 9
Enter an integer : 7
5 2 8 1 9 7
Process returned 0
DYNAMIC MEMORY ALLOCATION :
MALLOC() FUNCTION IN C:
Syntax of malloc( ) function :
Below is the source code for C Program to understand dynamic memory allocation using malloc( ) which is successfully compiled and run on Windows System to produce desired output as shown below :
SOURCE CODE : :
OUTPUT : :
need an explanation for this answer? contact us directly to get an explanation for this answer