0
Please tell me the difference between malloc calloc and realloc. Which one to use when. Thank you
2 odpowiedzi
+ 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);
}
+ 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.