
- C Programming Tutorial
- C - Home
- C - Overview
- C - Environment Setup
- C - Program Structure
- C - Basic Syntax
- C - Data Types
- C - Variables
- C - Constants
- C - Storage Classes
- C - Operators
- C - Decision Making
- C - Loops
- C - Functions
- C - Scope Rules
- C - Arrays
- C - Pointers
- C - Strings
- C - Structures
- C - Unions
- C - Bit Fields
- C - Typedef
- C - Input & Output
- C - File I/O
- C - Preprocessors
- C - Header Files
- C - Type Casting
- C - Error Handling
- C - Recursion
- C - Variable Arguments
- C - Memory Management
- C - Command Line Arguments
- C Programming useful Resources
- C - Questions & Answers
- C - Quick Guide
- C - Useful Resources
- C - Discussion
Explain malloc function in C programming
Problem
Write a C program to display and add the elements using dynamic memory allocation functions.
Solution
In C, the library function malloc allocates a block of memory in bytes at runtime. It returns a void pointer, which points to the base address of allocated memory and it leaves the memory uninitialized.
Syntax
void *malloc (size in bytes)
For example,
int *ptr;
ptr = (int * ) malloc (1000);
int *ptr;
ptr = (int * ) malloc (n * sizeof (int));
Note − It returns NULL, if the memory is not free.
Example
#include<stdio.h> #include<stdlib.h> void main(){ //Declaring variables and pointers,sum// int numofe,i,sum=0; int *p; //Reading number of elements from user// printf("Enter the number of elements : "); scanf("%d",&numofe); //Calling malloc() function// p=(int *)malloc(numofe*sizeof(int)); /*Printing O/p - We have to use if statement because we have to check if memory has been successfully allocated/reserved or not*/ if (p==NULL){ printf("Memory not available"); exit(0); } //Printing elements// printf("Enter the elements :
"); for(i=0;i<numofe;i++){ scanf("%d",p+i); sum=sum+*(p+i); } printf("
The sum of elements is %d",sum); free(p);//Erase first 2 memory locations// printf("
Displaying the cleared out memory location :
"); for(i=0;i<numofe;i++){ printf("%d
",p[i]);//Garbage values will be displayed// } }
Output
Enter the number of elements : 5 Enter the elements : 23 45 65 12 23 The sum of elements is 168 Displaying the cleared out memory location : 10753152 0 10748240 0 23
- Related Articles
- What is a malloc function in C language?
- malloc() vs new() in C/C++
- calloc() versus malloc() in C
- What is malloc in C language?
- Explain reference and pointer in C programming?
- Set find() function in C++ programming STL
- Explain monolithic and modular programming in C language
- Explain array of pointers in C programming language
- How do malloc() and free() work in C/C++?
- Explain Compile time and Run time initialization in C programming?
- Anonymous function in Dart Programming
- table.pack() function in Lua programming
- table.unpack() function in Lua programming
- math.ceil() function in Lua programming
- math.floor() function in Lua programming

Advertisements