Write a C Program for dynamic memory allocation using malloc( )

By | 19.03.2017

C Program to understand dynamic memory allocation


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.


DYNAMIC MEMORY ALLOCATION :


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

If you found any error or any queries related to the above program or any questions , doubts or reviews , you wanna to ask or share to us, you may Contact Us  through our contact Page or you can also comment below in the comment section.We will try our best to reach up to you in the short interval of time.


Thanks for reading the post.

0 0 votes
Article Rating
Category: C Programming Pointer Programs Tags:

About Tunde A

My name is Tunde Ajetomobi, a Tech Enthusiast and Growth Hacker. I enjoy creating helpful content that solves problem across different topics. Codezclub is my way of helping young aspiring programmers and students to hone their skills and find solutions on fundamental programming languages.

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments