- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How do malloc() and free() work in C/C++?
malloc()
The function malloc() is used to allocate the requested size of bytes and it returns a pointer to the first byte of allocated memory. It returns null pointer, if it fails.
Here is the syntax of malloc() in C language,
pointer_name = (cast-type*) malloc(size);
Here,
pointer_name − Any name given to the pointer.
cast-type − The datatype in which you want to cast the allocated memory by malloc().
size − Size of allocated memory in bytes.
Here is an example of malloc() in C language,
Example
#include <stdio.h> #include <stdlib.h> int main() { int n = 4, i, *p, s = 0; p = (int*) malloc(n * sizeof(int)); if(p == NULL) { printf("\nError! memory not allocated."); exit(0); } printf("\nEnter elements of array : "); for(i = 0; i < n; ++i) { scanf("%d", p + i); s += *(p + i); } printf("\nSum : %d", s); return 0; }
Output
Here is the output
Enter elements of array : 32 23 21 8 Sum : 84
free()
The function free() is used to deallocate the allocated memory by malloc(). It does not change the value of the pointer which means it still points to the same memory location.
Here is the syntax of free() in C language,
void free(void *pointer_name);
Here,
pointer_name − Any name given to the pointer.
Here is an example of free() in C language,
Example
#include <stdio.h> #include <stdlib.h> int main() { int n = 4, i, *p, s = 0; p = (int*) malloc(n * sizeof(int)); if(p == NULL) { printf("\nError! memory not allocated."); exit(0); } printf("\nEnter elements of array : "); for(i = 0; i < n; ++i) { scanf("%d", p + i); s += *(p + i); } printf("\nSum : %d", s); free(p); return 0; }
Output
Here is the output
Enter elements of array : 32 23 21 28 Sum : 104