Skip to content

Commit 7ef9e61

Browse files
committed
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`.
1 parent bedd572 commit 7ef9e61

File tree

1 file changed

+7
-3
lines changed

1 file changed

+7
-3
lines changed

storage/blockdevice/source/HeapBlockDevice.cpp

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ HeapBlockDevice::~HeapBlockDevice()
4040
{
4141
if (_blocks) {
4242
for (size_t i = 0; i < _count; i++) {
43-
free(_blocks[i]);
43+
delete[] _blocks[i];
4444
}
4545

4646
delete[] _blocks;
@@ -57,7 +57,11 @@ int HeapBlockDevice::init()
5757
}
5858

5959
if (!_blocks) {
60-
_blocks = new uint8_t *[_count];
60+
_blocks = new (std::nothrow) uint8_t *[_count];
61+
if (!_blocks) {
62+
return BD_ERROR_DEVICE_ERROR;
63+
}
64+
6165
for (size_t i = 0; i < _count; i++) {
6266
_blocks[i] = 0;
6367
}
@@ -156,7 +160,7 @@ int HeapBlockDevice::program(const void *b, bd_addr_t addr, bd_size_t size)
156160
bd_addr_t lo = addr % _erase_size;
157161

158162
if (!_blocks[hi]) {
159-
_blocks[hi] = (uint8_t *)malloc(_erase_size);
163+
_blocks[hi] = new (std::nothrow) uint8_t[_erase_size];
160164
if (!_blocks[hi]) {
161165
return BD_ERROR_DEVICE_ERROR;
162166
}

0 commit comments

Comments
 (0)