The name malloc and calloc() are library functions that allocate memory dynamically. It means that memory is allocated during runtime(execution of the program) from the heap segment.
- Initialization: malloc() allocates memory block of given size (in bytes) and returns a pointer to the beginning of the block. malloc() doesn’t initialize the allocated memory. If we try to access the content of memory block(before initializing) then we’ll get segmentation fault error(or maybe garbage values).
calloc() allocates the memory and also initializes the allocated memory block to zero. If we try to access the content of these blocks then we’ll get 0.
- Number of arguments: Unlike malloc(), calloc() takes two arguments:
1) Number of blocks to be allocated.
2) Size of each block.
- Return Value: After successful allocation in malloc() and calloc(), a pointer to the block of memory is returned otherwise NULL value is returned which indicates the failure of allocation.
- Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
- malloc() vs new
- what happens when you don't free memory after using malloc()
- Function Interposition in C with an example of user defined malloc()
- Difference between Iterators and Pointers in C/C++ with Examples
- Difference between Argument and Parameter in C/C++ with Examples
- Difference between C and C++
- Difference between C and C#
- Difference between ++*p, *p++ and *++p
- Difference between GCC and G++
- Difference between C and Python
- Difference between scanf() and gets() in C
- Difference between C and Dart
- Difference between while(1) and while(0) in C language
- Difference and Similarities between PHP and C
- Difference between Java and C language
- Difference between strncmp() and strcmp in C/C++
- Difference between Structure and Array in C
- Difference between Structure and Union in C
- Difference between fork() and exec()
For instance, If we want to allocate memory for array of 5 integers, see the following program:-
We can achieve same functionality as calloc() by using malloc() followed by memset(),
Note: It would be better to use malloc over calloc, unless we want the zero-initialization because malloc is faster than calloc. So if we just want to copy some stuff or do something that doesn’t require filling of the blocks with zeros, then malloc would be a better choice.
This article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.