malloc calloc

malloc calloc

malloc  returns a void pointer to the allocated space or  NULL if there is insufficient memory available. To return a pointer to a type other than void, use a type cast on the return value. The storage space pointed to by the return value is guaranteed to be suitably aligned for storage of any type of object.

If size is 0, malloc allocates a zero-length item in the heap and returns a valid pointer to that item. Always check the return from malloc, even if the amount of memory requested is small.

malloc() does not initialize the memory allocated, while calloc() initializes the allocated memory to ZERO.

calloc(m, n) is essentially equivalent to:

p = malloc(m * n);
memset(p, 0, m * n);  // setting value to zero

Allocation method for calloc , malloc :
int *ptr = malloc(10 * sizeof (int)); //The contents of allocated memory are not changed. i.e., the memory contains unpredictable or garbage values which creates a risk.
int *ptr = calloc(10,sizeof (int)); // The allocated region is initialized to zero.

Would following code work?

void allocateArray(int *array){


int main(){
int *array;

When calling allocateArray in main, you are passing array by value, so it is completely unchanged by the call to allocateArray . the “array” inside allocateArray is a copy of the original array from main(), and it is this copy that is assigned the result of the malloc call and  not the original array in main()

Why does malloc() return a void*?

It’s because malloc() has no idea which type of object we want to put in that memory.