The ones who are crazy enough to think they can change the world are the ones who do.- Steve Jobs
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.
void *calloc (size_t nitems, size_t size);
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); |
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.
#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; }
Check numbers[3] in the above output, clearly calloc() initializes the allocated block to 0's.
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.
#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; }
Check numbers[3] in the above output, clearly malloc() initializes the allocated block to some garbage value.
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.
We may make mistakes(spelling, program bug, typing mistake and etc.), So we have this container to collect mistakes. We highly respect your findings.
© Copyright 2019