Topics / C++ for Embedded / Q10
What is the difference between new/delete and malloc/free?
Short answer: new allocates memory and runs the constructor, returning a correctly typed pointer; delete runs the destructor and then frees the memory. malloc/free only allocate and free raw bytes and know nothing about constructors or types. By default new throws std::bad_alloc on failure (with exceptions disabled it typically aborts, so use new (std::nothrow) and check for null), while malloc returns NULL. Memory from new must be released with delete (and new[] with delete[]), never with free.
new / delete |
malloc / free |
|
|---|---|---|
| Constructors / destructors | yes | no |
| Returns | typed pointer | void * |
| Failure | throws bad_alloc (or nullptr with nothrow) |
NULL |
| Size | computed from the type | given in bytes |
| Customisable | per class (operator new) or globally |
wrap or replace the allocator |
| Arrays | new[] / delete[] (stores the count) |
manual |
Embedded considerations
- Both usually use the same heap (the default
operator newcallsmalloc), so fragmentation and non-deterministic timing apply equally. - You can override global
operator new/deleteto route allocations to an RTOS heap (pvPortMalloc), to a pool, or to trap any use after initialisation (call an error handler), enforcing a "no heap at run time" policy. - Placement new constructs an object in memory you already have, without allocating (next question).
- Class-specific
operator newcan allocate from a per-class pool: fast and fragmentation-free.