Chia-Network / bladebit

A high-performance k32-only, Chia (XCH) plotter supporting in-RAM and disk-based plotting
Apache License 2.0
339 stars 109 forks source link

Modernize memory management #328

Closed RnMss closed 1 year ago

RnMss commented 1 year ago

Use modern C++ memory management to avoid memory safety risks.

For example:

Replace Span holding allocated memory with std::vector.

Span<uint64> _c2Entries;
// on initialization
_c2Entries = Span<uint64>( new uint64[c2MaxEntries], c2MaxEntries );
// on destruction
delete[] _c2Entries.Ptr();

with

std::vector<uint64> _c2Entries;
// on initialization
c2MaxEntries.resize(c2MaxEntries);

Replace raw pointers holding allocated memory with std::unique_ptr<Type> / std::unique_ptr<Type[]>

uint64* _parkBuffer;
// on initialization
_parkBuffer = bbmalloc<uint64>( largestParkSize );
// on destruction
if (_parkBuffer) free(_parkBuffer);

with

std::unique_ptr<uint64[]> _parkBuffer;
// on initialization
_parkBuffer.reset(new uint64[largestParkSize]);

or

// If there is a reason we must use malloc/free rather than new/delete
std::unique_ptr<uint64[], void (*)(uint64*)> _parkBuffer{bbmalloc<uint64>(largestParkSize), &free};

For memory allocated with virtual-alloc, write an allocator and use std::vector.

Span<uint64> _c3Buffer;
// on initialization
_c3Buffer.values = bbcvirtallocbounded<uint64>( kCheckpoint1Interval * 2 );
_c3Buffer.length = kCheckpoint1Interval * 2;
// on destruction
bbvirtfreebounded(_c3Buffer.Ptr());

with

std::vector<uint64, bb_allocator> _c3Buffer;
// on initialize
_c3Buffer.resize( kCheckpoint1Interval * 2 );