C Books Guide and List
C++ Books Guide and List
Best Java Books

3,749 questions

4,049 answers

114 comments

10,705 users

What are the differences between malloc() and calloc()?

0 votes
39 views
asked Jan 8, 2014 by keem Expert (13,240 points)

1 Answer

0 votes
Allocation of memory at the time of execution is called dynamic memory allocation. It is done using the standard library functions malloc() and calloc(). It is defined in "stdlib.h". malloc(): used to allocate required number of bytes in memory at runtime. It takes one argument, viz. size in bytes to be allocated.

Syntax:

void * malloc(size_t size);

Example:

a = (int*) malloc(4);

4 is the size (in bytes) of memory to be allocated.

calloc(): used to allocate required number of bytes in memory at runtime. It needs two arguments viz.,

1. total number of data and

2. size of each data.

Syntax:

void * calloc(size_t nmemb, size_t size);

Example:

a = (int*) calloc(8, sizeof(int));

Here sizeof indicates the size of the data type and 8 indicates that we want to reserve space for

storing 8 integers.

 Differences between malloc() and calloc() are:

1. Number of arguments differ.

2. By default, memory allocated by malloc() contains garbage values. Whereas memory allocated by calloc() contains all zeros.
answered Jan 8, 2014 by rajesh Guru (39,140 points)

Related questions

0 votes
3 answers 49 views
0 votes
1 answer 22 views
22 views asked Dec 27, 2013 by john Guru (27,140 points)
0 votes
1 answer 29 views
29 views asked Dec 27, 2013 by john Guru (27,140 points)
+2 votes
1 answer 4,028 views
0 votes
2 answers 2,731 views
2,731 views asked Jul 7, 2011 by anonymous
...