Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

3. Pointers & Memory allocation There are two allocation functions: void *malloc

ID: 3794638 • Letter: 3

Question

3. Pointers & Memory allocation

There are two allocation functions:

void *malloc(size_t size) allocates size bytes, returns a pointer to the space. Returns NULL if memory is not available.

void *calloc(size_t num, size_t size) allocates space for num elements of size, clears the space, returns a pointer, or NULL if not available. Example: ptr = (int*)calloc(5, sizeof(int));

Release allocated memory back to the heap:

void free(void *ptr)

Which is less error-prone? Why?

Which one is more efficient? Why?

Explanation / Answer

a)calloc() allocates the memory and also initializes the allocates memory to zero where as malloc() doesn’t initialize the allocated memory.
so if the space allocated is to be filled by the user inputs or random numbers it doesn’t matter which function we use,
as malloc is using garbage values so we say it is more error prone as compared to calloc

b)calloc() allocates the memory and also initializes the allocates memory to zero where as malloc() doesn’t initialize the allocated memory as a result malloc is faster
than calloc it totally depends on the scenario you are using the functions If we do not want to initialize memory then malloc() is the obvious choice.
but if we want to initialise memory to zero we use calloc

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote