Requesting that new memory be cleared
In many situations we want our allocated memory to have a known value.
The C11 standard library provides a single function to provide the most
common case - clearing allocated memory:
#include <stdlib.h>
extern void *calloc( size_t nitems, size_t itemsize );
....
int *intarray = calloc(N, sizeof(int));
|
It's lost in C's history why malloc() and calloc()
have different calling sequences.
To explain what is happening, here,
we can even write our own version, if we are careful:
#include <stdlib.h>
#include <string.h>
void *my_calloc( size_t nitems, size_t itemsize )
{
size_t nbytes = nitems * itemsize;
void *result = malloc( nbytes );
if(result != NULL) {
memset( result, 0, nbytes ); // SETS ALL BYTES IN result TO THE VALUE 0
}
return result;
}
....
int *intarray = my_calloc(N, sizeof(int));
|
CITS2002 Systems Programming, Lecture 12, p8, 28th August 2024.
|