From 7ef9e6175f092c4009e49b28d4ebf0eebcfd81ba Mon Sep 17 00:00:00 2001 From: Lingkai Dong Date: Fri, 26 Mar 2021 17:11:35 +0000 Subject: [PATCH] HeapBlockDevice: allocate with std::nothrow Mbed OS does not enable C++ exceptions, so we should call `new` with `std::nothrow` which returns a C-style NULL pointer when allocation fails to allow error handling. For consistency of style within the same file, this commit also replaces `malloc()` and `free()` to `new (std::nothrow)` and `delete`. --- storage/blockdevice/source/HeapBlockDevice.cpp | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/storage/blockdevice/source/HeapBlockDevice.cpp b/storage/blockdevice/source/HeapBlockDevice.cpp index 65e5def5de..5994d6194b 100644 --- a/storage/blockdevice/source/HeapBlockDevice.cpp +++ b/storage/blockdevice/source/HeapBlockDevice.cpp @@ -40,7 +40,7 @@ HeapBlockDevice::~HeapBlockDevice() { if (_blocks) { for (size_t i = 0; i < _count; i++) { - free(_blocks[i]); + delete[] _blocks[i]; } delete[] _blocks; @@ -57,7 +57,11 @@ int HeapBlockDevice::init() } if (!_blocks) { - _blocks = new uint8_t *[_count]; + _blocks = new (std::nothrow) uint8_t *[_count]; + if (!_blocks) { + return BD_ERROR_DEVICE_ERROR; + } + for (size_t i = 0; i < _count; i++) { _blocks[i] = 0; } @@ -156,7 +160,7 @@ int HeapBlockDevice::program(const void *b, bd_addr_t addr, bd_size_t size) bd_addr_t lo = addr % _erase_size; if (!_blocks[hi]) { - _blocks[hi] = (uint8_t *)malloc(_erase_size); + _blocks[hi] = new (std::nothrow) uint8_t[_erase_size]; if (!_blocks[hi]) { return BD_ERROR_DEVICE_ERROR; }