Compare C++ new, malloc, and Placement new
Company: Hudson
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: medium
Interview Round: Technical Screen
# Compare C++ new, malloc, and Placement new
Explain what happens when a C++ `new` expression is evaluated, how it differs from `malloc`, what placement `new` does, and when constructing objects in caller-supplied storage can improve performance. Include destruction, alignment, exception safety, and object lifetime.
### Constraints & Assumptions
- Discuss non-array objects first and call out where arrays add complexity.
- Distinguish a `new` expression from allocation functions named `operator new`.
- Assume modern C++ object-lifetime and alignment rules.
- Do not treat an allocator or memory pool as automatically faster without a workload.
### Clarifying Questions to Ask
- Should custom allocation functions and allocator-aware containers be included?
- Is the use case a pool, arena, shared-memory region, or fixed buffer?
- Are over-aligned types and exception-free environments in scope?
- Who owns the storage and when may it be reused?
### Hints
- Allocation and construction are distinct operations.
- Placement `new` does not allocate the supplied buffer.
- Destruction and deallocation must mirror the way lifetime and storage began.
### What a Strong Answer Covers
- Storage allocation, alignment, constructor invocation, failure, and cleanup in a `new` expression.
- Raw byte allocation from `malloc`, explicit construction needs, and matching `free`.
- Placement construction, caller-owned storage, explicit destruction, reuse, and lifetime rules.
- Pools and arenas, locality, batching, fragmentation, determinism, and measurement.
- RAII, exception safety, arrays, over-alignment, and undefined behavior from mismatched cleanup.
- Preference for standard containers and allocators over ad hoc memory management when possible.
### Follow-up Questions
1. What happens if a constructor throws after storage was allocated by a `new` expression?
2. Why must placement-constructed objects usually be destroyed explicitly?
3. When is `std::launder` relevant to storage reuse?
4. How would you make an object pool safe under concurrency and exceptions?
Quick Answer: Compare a C++ new expression, malloc, and placement new by separating storage allocation from object construction. Cover alignment, constructors, exceptions, explicit destruction, matching deallocation, object lifetime, pools, arenas, locality, and RAII safety.