Dynamic Memory Interview Questions

From Embedded Systems Learning Academy
Jump to: navigation, search

How does free() deallocate memory when no data related to size is passed as a parameter?

The memory allocation functions are implemented in such a way that certain metadata for each allocated block is stored in-line or separately.

Considering in-line metadata, the header information contains the size which is checked by free to understand how much of memory needs to be deallocated.

What happens when free() is called on an already freed pointer?

The behaviour is undefined. It could result in a crash, memory corruption or a segmentation fault.
A good practise is to make the pointer a NULL after freeing.

free(pointer_to_be_freed);
pointer_to_be_freed = nullptr;

How can primitive data types be allocated using new?

int* i = new int(6);


What are the differences between new and malloc?

malloc new
1 malloc is a function call new is an operator and can be overloaded
2 malloc is concerned with basic memory allocation new invokes the constructor
3 malloc returns a pointer to the memory block allocated which is of type void new returns a pointer of the exact datatype requested
4 malloc never throws exceptions. On failure, it returns a NULL pointer On failure, new throws std::bad_alloc exception