Difference between malloc, calloc, free and realloc in C/C++

0 votes
asked in Interview Question by admin
reshown by admin
What is difference between malloc, calloc, free and realloc in C/C++?
Add question to:

1 Answer

+1 vote
answered by kumar
selected by admin
 
Best answer

1.malloc(Allocates uninitialized memory): malloc allocates new memory on heap and content of the memory allocated is garbage.
If it is not possible to allocate this function returns NULL.
Example:  
int * ptr = (int*) malloc(100 * sizeof(long));

2.calloc(Allocates initialized memory): calloc is all the same as malloc as malloc except it allocates memory and initialized it with zero.
Example:
Allocating memory for an array of 10 elements of type int. 
int *ptr = (int*) calloc(10 ,sizeof (int));

3.realloc(changes the size of already allocated memory): It is used to reduce and increase size of already allocated space/memory.It keeps previous content as it is.Like if we had memory for 10 integers and they were initialized with content 2.If we increase this memory size for 20 integeres using realloc then content of first 10 integers is not changed , only extra memory is added.Sometimes it is not possible to allocate memory at the same place where already created space exists then it copy all the previous content to a new location and then increase size of memory so it changes the base address of already created memory.So if you are using old memory pointer then it may cause dangling pointer problem.
Example: 

  int * ptr1 = (int*) malloc(10 * sizeof(int));‚Äč
  int * ptr2 ;
  ptr2 = (int*) realloc(ptr2, 20 * sizeof(int));
ptr1 may or may not equal to ptr2

...