Interview question

Interview Question on malloc, calloc, realloc and free.

What is the difference between malloc and calloc?

  • One of the major differences between malloc() and calloc() is that in the case of malloc() the memory which is allocated is not initialized whereas in the case of calloc() the memory which is allocated is set to 0 that is every bits is set to 0.
  • malloc() is faster than calloc() as in the case of Calloc, one extra operation that is setting the memory to 0 is performed unlike malloc().

Is malloc a system call?

No, malloc(), calloc() or realloc() are c libraries that internally use other system call like brk() and sbrk().

How does free work or why in free size is not given to be freed?

When we allocate memory, there is a special block that holds the metadata in the pointer variable and this metadata contains size of the memory allocated.

Thus when we use the pointer variable in the free(), we do not need to pass the size of the memory to be freed as malloc or calloc keeps track of size of each block as a metadata.

untitled image

Do we need to type cast malloc?

In C, we don’t need to cast the return value of malloc. The pointer to void returned by malloc is automatically converted to the correct type. However, if we want our code to compile with a C++ compiler, a cast is needed.

What happens when we give 0 as the size to be allocated in malloc or calloc?

If the size passed to malloc is 0, then it either returns NULL or a unique pointer value which can be passed to free. In generic way its behavior is undefined.

How do you implement calloc using malloc?

A call to calloc() is equivalent to a call to malloc() followed by one to memset(). calloc(m, n) is essentially equivalent to:

p = malloc (m * n);
memset(p, 0, m * n);

p = malloc (m * n);

memset(p, 0, m * n);

Relevant Posts:

Categories: C Language

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: