top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Which one is better to use in dynamic memory allocation malloc() or calloc(), please explain with appropriate example ?

0 votes
757 views
Which one is better to use in dynamic memory allocation malloc() or calloc(), please explain with appropriate example ?
posted Apr 19, 2017 by Anirudha Sarkar

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+2 votes

malloc() takes a single argument (memory required in bytes), while calloc() needs two arguments.
calloc() initializes the allocated memory to ZERO and malloc does not
calloc() allocates a memory area, the length will be the product of its parameters.

Example
ptr = (char **) malloc (20); // allocates 20 bytes of memory
ptr = (char **) calloc (20, sizeof(char*)); // allocates 100 bytes assuming the pointer size is 4

Which one is better is dependent on context none is better or worse.

answer Apr 19, 2017 by Leon Martinović
here is example to allocate array using malloc witch size(number of elements) is defined by input from user,fill it with values and print.

#include <stdio.h>
#include<stdlib.h>


int main(void)
{
int size,i;
int *p;

printf("enter the number of elemnts in array : ");
scanf("%d",&size);

p = (int*)malloc(size*sizeof(int));

i=0;

while(i != size)
{
scanf("%d",&i[p]);
i++;    
}

i=0;

while( i != size)
{
printf("%d element is  : %d\n",(i+1),i[p]);
i++;
}

free(p);

getchar();  /*  this is yust for stoping
getchar();                program */
return 0;
}
for calloc it will be somthing like this


p = (int*)calloc(size,sizeof(int));
0 votes

This video will help you if it does not help you , I will write an explanation

answer Apr 19, 2017 by Leon Martinović
...