What is a memory leak, and how do smart pointers help prevent them?
Last updated
A memory leak is heap memory that is allocated but never freed because the program loses every reference to it, so it stays reserved until the process ends. Smart pointers prevent this by binding deallocation to ownership and scope (RAII), removing the need for manual delete.
How leaks happen: Forgetting
delete, an early return or exception skipping cleanup, or overwriting the only pointer to a block.How smart pointers help:
unique_ptrfrees its object automatically when it goes out of scope, even on exceptions.shared_ptrfrees when the last owner is destroyed, so cleanup happens exactly once.
Limits:
shared_ptrcycles still leak: break them withweak_ptr.Prefer
make_unique/make_sharedand avoid raw owning pointers entirely.
- https://www.interviewbit.com/cpp-interview-questions/
- https://blog.mettl.com/cpp-interview-question/
- https://www.wecreateproblems.com/interview-questions/cpp-interview-questions
- https://www.scribd.com/document/849800819/Cognizant-Latest-Interview-Experience-27-28-March-Interview-Questions
- https://www.acte.in/c-and-c-plus-plus-interview-questions-and-answers
- https://github.com/Devinterview-io/cpp-interview-questions
- https://perfectnotes.org/interview-questions/cpp/top-50-cpp-interview-questions