All of the answers here have been "be careful!", and "use good programming practices!".
That's not a very satisfying answer. These problems have existed in C for 40+ years, and they are still common in any C++ project of significant size.
The biggest guidelines you'll hear people recommend are:
- Use smart pointers
- Use RAII
Both are true, but there is more you can do.
In 2015, the Standard C++ Foundation released the Guidelines Support Library.
You can write C++ programs that are statically type safe and have no
resource leaks. You can do that without loss of performance and
without limiting C++’s expressive power. This model for type- and
resource-safe C++ has been implemented using a combination of ISO
standard C++ language facilities, static analysis, and a tiny support
library (written in ISO standard C++).
I recommend you use GSL's Owner<>
with a static analysis tool.
That will guarantee safe behaviour.