3 ms·
Memory safety issues in C++ have two main causes. One is object lifetime. The other is pointers. If at all possible you want to design your program such that ob
by gizmo 3y ago
Memory safety issues in C++ have two main causes. One is object lifetime. The other is pointers. If at all possible you want to design your program such that object lifetime is completely obvious and predictable. Use sentinels and tombstones instead of null pointers. Use arenas wherever possible. During debug use an allocator that doesn't reuse memory (just mark the pages as no access so you will segfault when trying to read/write in previously freed memory). When object lifetime is complex you can give objects a "color" during allocation and then make rules that you can verify that objects of one color can never have pointers to objects of another color, or that an object can never contain a pointer to a younger object. You can eliminate entire categories of memory problems this way. Instead of pointers use indices and a getter function. In debug mode the getter can check if the right locks are held, scan the heap for incorrect pointers, check for ownership flags, etc. Actually take advantage of the virtual memory tools provided to you by the operating system. Threadlocal memory. Fork tasks into different processes. Actually use mprotect and the like.
Zero memory safety mistakes is a tall order. But the overwhelming majority of memory errors we see in the wild can be easily prevented by good practices. And for the memory errors that do happen stack protection flags make a big difference (https://developers.redhat.com/articles/2022/06/02/use-compiler-flags-stack-protection-gcc-and-clang# https://developers.redhat.com/articles/2022/06/02/use-compil...).