Skip to content

[C++] HeapResizableDirectMemory copy constructor writes through nullptr and stores the end iterator as Pointer #121

Backlog

Description

@konard

Problem

HeapResizableDirectMemory.h:41-51:

HeapResizableDirectMemory(const HeapResizableDirectMemory& other)
{
    auto mem = Internal::as_bytes(other.Pointer(), other.UsedCapacity());
    Pointer() = std::copy(std::execution::par_unseq, mem.begin(), mem.end(), static_cast<std::byte*>(Pointer()));
    ReservedCapacity(other.ReservedCapacity());
    UsedCapacity(other.UsedCapacity());
}
  • Pointer() is still nullptr when std::copy runs, so the bytes are written to address 0.
  • The result of std::copy (the end iterator) is stored as Pointer(), and realloc is later called on it.
  • OnReservedCapacityChanged also loses the old block when realloc fails (Pointer() = std::realloc(Pointer(), …)).

The existing test GetLastByteByCopy passes this constructor only because UsedCapacity() is 0 there: zero bytes are copied, the "end iterator" is nullptr, and realloc(nullptr, n) behaves like malloc. The test then reads an uninitialised byte of a fresh block and does not check the copy.

Reproduction

experiments/issue-94-cpp-probes, GCC 13 with -fsanitize=address,undefined, copying a memory with UsedCapacity(16):

/usr/include/c++/13/pstl/algorithm_impl.h:877:81: runtime error: store to null pointer of type 'byte'

Proposed solution

  • Allocate first (ReservedCapacity(other.ReservedCapacity())), then copy into the new block, and keep Pointer() pointing at the block start.
  • Use the copy-and-swap idiom; add a move constructor and move assignment.
  • Handle a realloc that returns nullptr (throw std::bad_alloc and keep the old block).
  • Add a gtest with a non-empty source.

Part of #94 (catch up with mem-rs). Analysis and evidence: case study.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugcpp

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions