The ones who are crazy enough to think they can change the world are the ones who do.
- Steve Jobs

C Calloc()

Why Calloc?

Now it's time to partition the microprocessor's memory to your 6 teams of your startup company, If you want to allocate non-consecutive memory location to every team, then calloc() will help you out there.

calloc in c

What is Calloc?

  • calloc() is the programmer's shorthand to represent clear allocation.
  • calloc() allocates a block of size bytes to a program from the heap.
  • calloc() allocate an exact quantity of memory explicitly to a program, when required.
  • allocation of memory is done in non-consecutive memory location.

Calloc() Syntax

Syntax
void *calloc  (size_t nitems, size_t size);

calloc() vs malloc()

Type calloc() malloc()
Number of argruments 2 1
Block Initialization 0 some garbage value
say 2563547
Return value (success) malloc() returns a pointer to the newly allocated block of memory calloc() returns a pointer to the newly allocated block of memory
Return value (failure) malloc() returns NULL calloc() returns NULL
syntax void *calloc (size_t nitems, size_t size); void *malloc (size_t size);

C Program - Using Calloc()

From the following program we will prove that a memory blocks which are allocated by using calloc() will be represented by a value zero in it.

calloc-1.c
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *numbers = (int*)calloc(4, sizeof(int));
int i;
numbers[0] = 1;
numbers[1] = 2;
numbers[2] = 3;
printf("\nStored integers are ");
for(i = 0; i < 4; i++)
printf("\nnumbers[%d] = %d ", i, numbers[i]);
return 0;
}
  • numbers[0] = 1
  • numbers[1] = 2
  • numbers[2] = 3
  • numbers[3] = 0

Note:

Check numbers[3] in the above output, clearly calloc() initializes the allocated block to 0's.

Same C program - using malloc().

Let's do the same program using malloc() function to prove that a memory blocks which are allocated by using malloc() will be represented by some garbage value in it.

calloc-2.c
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *numbers = (int*)malloc(4* sizeof(int));
int i;
numbers[0] = 1;
numbers[1] = 2;
numbers[2] = 3;
printf("\nStored integers are ");
for(i = 0; i < 4; i++)
printf("\nnumbers[%d] = %d ", i, numbers[i]);
return 0;
}
  • numbers[0] = 1
  • numbers[1] = 2
  • numbers[2] = 3
  • numbers[3] = 1549890657

Note:

Check numbers[3] in the above output, clearly malloc() initializes the allocated block to some garbage value.

Did You Know?

malloc() leads to a security risk because its unpredictable whether the block of memory is allocated or not, as it represent every individual allocated block with some garbage value whereas calloc() represents by zero.

Report Us

We may make mistakes(spelling, program bug, typing mistake and etc.), So we have this container to collect mistakes. We highly respect your findings.

Report