Frequently Asked Questions related to Dynamic Memory Allocation
From Embedded Systems Learning Academy
Revision as of 05:29, 18 December 2016 by Proj user18 (talk | contribs)
1. 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 an in-line metadata, the header information contains the size which is checked by free to understand how much of memory needs to be deallocated.
2. 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;
3. How can primitive data types be allocated using new?
int* i = new int(6);
4. 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 |