From Diffen

[Edit Comparison Table]
Similarities (1) Differences (3) Show All (4)
Calloc Malloc
Syntax:void *calloc(size_t nelements, size_t bytes);void *malloc(size_t size);
Function:allocates a region of memory large enough to hold "nelements" 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.
Return value:void pointer (void *)void pointer (void *)
Number of arguments:21


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


[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); 
memset(p, 0, m * n);


Calloc vs. Malloc - Chat Room

Edit Article
Diffen on Facebook

Comments: Calloc vs Malloc  [Add Comments]


There are no comments for Calloc vs Malloc. You can post a comment.