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){

array=(int*)malloc(100);
array[0]=10;
}

int main(){
int *array;
allocateArray(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.

Resolving technical problems:

Solve your technical problems instantly

We provide Remote Technical Support from Monday to Sunday, 7:00PM to 1:00 AM

Mail your problem details at writeulearn@gmail.com along with your mobile numberand we will give you a call for further details. We usually attend your problems within 60 minutes and solve it in maximum 2 days.

Leave a Reply

Your email address will not be published. Required fields are marked *