What is the difference between
new/deleteandmalloc/free?newallocates memory and runs the constructor, anddeleteruns the destructor before freeing;mallocandfreeonly handle raw bytes.newis also type safe and throwsstd::bad_allocon failure, wheremallocreturnsNULL.Mixing them (
newwithfree,new[]withdelete) is undefined behavior.What is the difference between stack and heap memory in C++?
Local variables live on the stack and are destroyed when their scope ends; objects from
newlive on the heap until freed. The stack is fast but small, so deep recursion overflows it: 1 MB by default on Windows (see the /STACK linker option) and usually 8 MB on Linux. The heap is larger and slower, and its bugs are leaks and use after free.std::vector<int> v(1000000);puts thevectorobject on the stack and its ints on the heap.What is the difference between
deleteanddelete[]?delete pdestroys one object fromnew;delete[] pdestroys an array fromnew T[n], calling every element's destructor. The wrong form is undefined behavior: for elements with a destructor the compiler usually stores the count before the array, and onlydelete[]reads it. Preferstd::vectororstd::make_unique<int[]>(n).What is a memory leak in C++, and how do you find and prevent one?
Heap memory that is never freed, because nothing points to it any more or the code that frees it never runs. Typical causes are
newwithoutdeleteon an exception path, a missing virtual destructor, andshared_ptrcycles.Find leaks with Valgrind or AddressSanitizer. Prevent them with RAII: containers and
std::unique_ptrinstead of rawnew.What is RAII in C++?
RAII ties a resource to an object's lifetime: the constructor acquires it (memory, a file, a mutex) and the destructor releases it. Destructors run at scope end, including during stack unwinding, so release is guaranteed.
C++#include <iostream> #include <stdexcept> using namespace std; struct File { File() { cout << "open\n"; } ~File() { cout << "close\n"; } }; void work() { File f; throw runtime_error("disk full"); } int main() { try { work(); } catch (const exception& e) { cout << "caught: " << e.what() << "\n"; } }This prints
open,close, thencaught: disk full.std::vector,std::unique_ptrandstd::lock_guardwork this way, which is why C++ has nofinally.What are smart pointers in C++? Explain
unique_ptr,shared_ptrandweak_ptr.RAII wrappers that delete the object they own.
std::unique_ptrhas one owner, can only be moved and costs nothing extra.std::shared_ptrshares ownership through a reference count.std::weak_ptrobserves ashared_ptrwithout owning it.C++#include <iostream> #include <memory> #include <string> using namespace std; int main() { auto p = make_unique<string>("hi"); auto q = std::move(p); // ownership moves, p becomes empty cout << (p ? "p owns" : "p is empty") << ", q = " << *q << "\n"; }This prints
p is empty, q = hi. Default tounique_ptr. More in the smart pointers docs.Practice it: Implement Trie (Prefix Tree)
What is placement new, and when is it used?
new (address) T(args)constructs an object in memory you already own, without allocating.std::vectorrelies on it: the capacity beyondsize()is raw memory, andpush_backconstructs the new element there.C++#include <iostream> #include <new> #include <string> using namespace std; int main() { alignas(string) unsigned char buffer[sizeof(string)]; string* s = new (buffer) string("built in my buffer"); // no allocation for the object cout << *s << "\n"; s->~string(); // destroy it yourself; never delete }It prints
built in my buffer. The rules: the buffer must be large enough and aligned forT, you call the destructor yourself, and you neverdeletethe pointer. Memory pools and arena allocators use the same technique, and C++20 addsstd::construct_atas a safer spelling.
C++ Memory Management and Smart Pointers Interview Questions
new and delete, stack vs heap, leaks, RAII and the three smart pointers.
10 questions