Search code examples
c++memory-managementmemory-safety

What does it take to write memory safe C++ applications?


Is it possible to either create a coding standard or use of a library that can be proved to eliminate any memory management errors in C++?

I'm thinking of something like Java, it is just impossible to for example have dangling pointers in Java applications.


Solution

  • Is it possible to either create a coding standard or use of a library that can be proved to eliminate any memory management errors in C++?

    Yes and no.

    Even if you use a very strict standard, doing so will limit you to a very narrow subset of the C++ language. For example, the Power of Ten (Rules for Developing Safety-Critical Code) says that you should disable heap usage entirely. However that alone doesn't stop you from creating memory corruption.

    I think if there were an exact answer to this question, the industry would've solved this decades ago, but here we are...

    I don't believe that there is a definite way to make sure your code is totally safe, but there are best practices which will help you make sure there are as few problems as possible.

    Here are some suggestions:

    • As mentioned earlier, disallowing heap usage entirely might help you get rid of all the memory management problems, but it doesn't solve the problem completely because it doesn't save you from eg. stray pointer writes.
    • I recommend you read the about The Rule of Three, Five and Zero which explain some of the stuff you need to take care of.
    • Instead of managing memory on your own, use smart pointers like shared_ptr, unique_ptr etc. But course, you could still abuse these if you wanted to. (For example shared_ptr will not help you if you have circular references...)
    • Use memory checker tools like valgrind, which can help you discover problems and verify that your code is error-free.

    Even if you keep to any coding standard or best practice, errors can and will happen. Nobody guarantees that you will be safe. However, by keeping to these suggestions you can minimize the chance and impact of errors.