Pedro Kali Pedro Kali - 2 months ago 8
C Question

Initialize malloc in zeros instead of using calloc

I want to create dynamic array in the heap using

malloc
.

int *c = malloc(5 * sizeof(int));


The problem is that it is not initialized by zero and I'd like avoid using
calloc
as much as I can since I don't know how safe it is.

If I use
calloc
, is it going to do the same
malloc
job?

Answer

malloc():

malloc() takes one arguement: the amount of bytes to be allocated. It does not initialize the bytes to zero.

Code Sample:

int *mem = malloc(5 * sizeof(int));


calloc():

calloc() takes two arguements: the amount of elements to allocate memory for and the amount of memory that needs allocated for each element. It initializes each byte to zero.

Code Sample:

int *mem = calloc(5, sizeof(int));

Alternatively, you can initialize memory with memset()

#include <string.h> // for memset()

//allocate memory
int *mem = malloc(5 * sizeof(int));

//initialize memory to zeros
memset(mem, 0, 5 * sizeof(int));
Comments