A new release of the project memsafe has been published by rsashka. This project implements a mechanism for safe operation with reference types and dynamic memory in C++ code. The added protection does not disrupt reverse compatibility with old C++ code. The project consists of a single header file memsafe.h and a custom compiler. The code is distributed under the LGPL 2.1 license.
To ensure safe memory management, the concept of protection from the language Newlang is utilized, adapted for C++ and enhanced by checking the validity of reference types. Safety in managing dynamic memory relies on both strong and weak pointers, and monitoring the lifespan of copies of variables with strong pointers during program source code compilation.
The protection technique employed resembles the ownership and borrowing concept from the Rust language, but it is built on strong and weak links using standard C++ mechanisms such as shared_ptr and weak_ptr. All operations on data for a variable through a link can only occur after capture, i.e., after converting a weak link (weak_ptr) into a strong one (shared_ptr).
Object labeling in the library code is achieved through C++ attributes “[[Memsafe(…)]]”, reminiscent of a technique proposed by Bjarne Stroustrup and Herb Sutter, though it does not necessitate the creation of a new C++ standard as C++ 20 already offers sufficient support.
An example of the analyzer plugin’s functioning on code:
STD::Vector vec(100000, 0); auto x = vec.begin(); auto y = vec.end(); vec = {}; vec.shrink_to_fit(); STD::sort(x, y); // Malloc(): Unaligned Tcache Chunk Detected or Segmentation Fault
Command line to initiate the compiler with the plugin: