Calloc vs Malloc

Calloc and Malloc are both functions in C for allocating a block of memory.


Comparison chart

 
Improve this chart Calloc Malloc
Number of arguments: 2 1
Stands for: Blocks of Memory -Allocation Bytes of Memory allocation
Return value: void pointer (void *) void pointer (void *)
Syntax: void *calloc(size_t nelements, size_t bytes); void *malloc(size_t size);
Function: allocates a region of memory large enough to hold "n elements" of "size" bytes each. The allocated region is initialized to zero. allocates "size" bytes of memory. If the allocation succeeds, a pointer to the block of memory is returned.

Contents

edit Syntax and Examples

malloc()

void *malloc(size_t size);

allocates size bytes of memory. If the allocation succeeds, a pointer to the block of memory is returned. Example:

/* Allocate space for an array with ten elements of type int. */
int *ptr = malloc(10 * sizeof (int));
if (ptr == NULL) {
   /* Memory could not be allocated, so print an error and exit. */
   fprintf(stderr, "Couldn't allocate memory\n");
   exit(EXIT_FAILURE);
} 
/* Allocation succeeded. */


calloc()

void *calloc(size_t nelements, size_t bytes);

allocates a region of memory large enough to hold nelements of size bytes each. The allocated region is initialized to zero. In the above example:

/* Allocate space for an array with ten elements of type int. */
int *ptr = calloc(10,sizeof (int));
if (ptr == NULL) {
   /* Memory could not be allocated, so print an error and exit. */
   fprintf(stderr, "Couldn't allocate memory\n");
   exit(EXIT_FAILURE);
} 
/* Allocation succeeded. */


edit Related Information

  • malloc() does not initialize the memory allocated, while calloc() initializes the allocated memory to ZERO.
  • calloc(m, n) is the same as
p = malloc(m * n); 
if(p) memset(p, 0, m * n);

edit Further Reading

There are some good books available on Amazon.com for further reading on C programming:

edit See Also

Comments: Calloc vs Malloc

Comment anonymously

Anonymous comments

nice clearification..................apreciated work .....good job.:)

1.✗.✗.116 on 2013-03-15 10:29:07

Prasanna - Good Explaination..!!!

90.✗.✗.42 on 2010-12-06 10:05:36

I appreciate the clarification!

152.✗.✗.33 on 2010-08-25 13:40:53

Related Categories

  1. Programming
  2. Software
Search for a comparison
Mail