- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Articles
- What is the difference between new/delete and malloc/ free in C/ C++?
- How do exceptions work in C++
- How do interfaces work in C#?
- How do arrays work in C#?
- malloc() vs new() in C/C++
- How do inline variables work in C++/C++17?
- How do conversion operators work in C++?
- calloc() versus malloc() in C
- What is malloc in C language?
- Explain malloc function in C programming
- delete() and free() in C++
- Delete and free() in C++ Program
- What is a malloc function in C language?
- Employee Free Time in C++
- A, B and C can do a piece of work in 20,30 and 60 days respectively. In how many days can A do the work if he is assisted by B and C on every third day?
