Please tell me the difference between malloc calloc and realloc. Which one to use when. Thank you

29th Apr 2017, 1:03 PM
Amit Kumar
Amit Kumar - avatar
2 Antworten
+ 1
//**in c++*/ malloc - memory allocation - to allocate memory on a heap. void * malloc(size_t size); The calloc function allocates n objects of size m and fills them with zeros. Usually it is used to allocate memory for arrays. void* calloc(size_t num, size_t size); realloc (re-allocation) - allows you to change the size of previously allocated memory and receives as arguments the old pointer and the new memory size in bytes void* realloc(void* ptr, size_t size); After we have worked with memory, it is necessary to free memory by the function free: #include <conio.h> #include <stdio.h> #include <stdlib.h> void main() { int *p = NULL; p = (int*) malloc(100); free(p); }
29th Apr 2017, 1:20 PM
Nikita Kalitin
Nikita Kalitin - avatar
+ 1
calloc - Calloc also allocates memory on heap like malloc does. The only difference is that calloc also initialize the memory with zero. Realloc - Changes the size of memory block on heap. Suppose a pointer - ptr, is pointing to a memory of 10int on heap. You want to increase the size of memory pointed to by ptr from 10 to 20, without loosing the contents of already allocated memory using realloc.
6th Feb 2019, 3:29 PM
Wasula Benjamin
Wasula Benjamin - avatar