Pedro Kali Pedro Kali - 1 year ago 74
C Question

Initialize malloc in zeros instead of using calloc

I want to create dynamic array in the heap using


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

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

If I use
, is it going to do the same

Answer Source


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() 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));