Overload allocation and deallocation functions as a pair in the same scope.

Overload allocation and deallocation functions as a pair in the same scope.

Vulernability and risk

Failure to overload the corresponding dynamic storage function is likely to violate rules such as MEM51-CPP. Properly deallocate dynamically allocated resources. For instance, if an overloaded allocation function uses a private heap to perform its allocations, passing a pointer returned by it to the default deallocation function will likely cause undefined behavior. Even in situations in which the allocation function ultimately uses the default allocator to obtain a pointer to memory, failing to overload a corresponding deallocation function may leave the program in an unexpected state by not updating internal data for the custom allocator.

Mitigation and prevention

If an allocation function is overloaded in a given scope, the corresponding deallocation function must also be overloaded in the same scope (and vice versa).


1  #include <Windows.h>
2  #include <new>
4  extern "C++" void update_bookkeeping(void *allocated_ptr, std::size_t size, bool alloc);
6  void *operator new(std::size_t size) noexcept(false) {     // uncompliant code, it only overloads 'new' in std namespace, not 'delete'.
7    static HANDLE h = ::HeapCreate(0, 0, 0); // Private, expandable heap.
8    if (h) {
9      return ::HeapAlloc(h, 0, size);
10   }
11   throw std::bad_alloc();
12 }
14 struct S_positive {
15   void *operator new(std::size_t size) noexcept(false) {
16     void *ptr = ::operator new(size);
17     update_bookkeeping(ptr, size, true);                        // uncompliant code
18     return ptr;
19   }
20 };
22 struct S_negative {                                                        // compliant code
23   void *operator new(std::size_t size) noexcept(false) {
24     void *ptr = ::operator new(size);
25     update_bookkeeping(ptr, size, true);
26     return ptr;
27   }
29   void operator delete(void *ptr, std::size_t size) noexcept {
30     ::operator delete(ptr);
31     update_bookkeeping(ptr, size, false);
32   }
33 };

There is no corresponded deallocation method overloaded in the same scope for the allocation methods in line 6, and 15. The compliant situation is the allocation method overloaded in line 38 because there is the corresponded deallocation method overloaded in line 29.