top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is the difference between calloc() and malloc() in c ?

0 votes
458 views
What is the difference between calloc() and malloc() in c ?
posted Jul 23, 2014 by Chahat Sharma

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

1 Answer

+1 vote

malloc(): Allocates requested size of bytes and returns a pointer first byte of allocated space. The contents of allocated memory are not changed. i.e., the memory contains unpredictable or garbage values. This presents a risk.
calloc(): Calculates the size to be allocated and allocates, initializes it to zero and then returns a pointer to memory.

Syntax

void *malloc (size_in_bytes);
void *calloc (number_of_blocks, size_of_each_block_in_bytes);

Example

int * array;
if ( NULL == (array = malloc(10 * sizeof(int))) ) {
  printf("malloc failed\n");
  return(-1);
}

int * array;
if ( NULL == (array = calloc(10, sizeof(int))) ) {
  printf("calloc failed\n");
  return(-1);
}
answer Jul 23, 2014 by Salil Agrawal
Similar Questions
+4 votes

what is difference between new and malloc ??

+4 votes

I believe option 1 is more correct, dont know why?

1) int *p = malloc(sizeof(int)*l);
2) int *p = (int *)malloc(sizeof(int)*l);
...