From d16db180d37a346c1dfa8019eed3c9e79e760522 Mon Sep 17 00:00:00 2001 From: Marco Casaroli Date: Tue, 31 Jan 2023 14:36:56 +0100 Subject: [PATCH] Do not break if malloc size is zero MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit I get a scenario where `size_` is `0` so there is nothing to `malloc()`. According to `malloc(3)`: If size is 0, then malloc() returns either NULL, or a unique pointer value thatcan later be success‐fully passed to free(). According to `free(3)`: If ptr is NULL, no operation is performed. So, if `size_` is null and `_data` also, there is no OOM error. We can adjust the assert to not fail on this scenario. --- src/blob.hpp | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/src/blob.hpp b/src/blob.hpp index 06a41913..d84bba64 100644 --- a/src/blob.hpp +++ b/src/blob.hpp @@ -81,7 +81,7 @@ struct blob_t _size (size_), _owned (true) { - alloc_assert (_data); + alloc_assert (!_size || _data); } // Creates a blob_t of a given size, an initializes content by copying @@ -91,8 +91,10 @@ struct blob_t _size (size_), _owned (true) { - alloc_assert (_data); - memcpy (_data, data_, size_); + alloc_assert (!size_ || _data); + if (size_ && _data) { + memcpy (_data, data_, size_); + } } // Creates a blob_t for temporary use that only references a @@ -126,10 +128,12 @@ struct blob_t { clear (); _data = static_cast (malloc (other_._size)); - alloc_assert (_data); + alloc_assert (!other_._size || _data); _size = other_._size; _owned = true; - memcpy (_data, other_._data, _size); + if (_size && _data) { + memcpy (_data, other_._data, _size); + } } // Sets a blob_t to a copy of a given buffer. @@ -137,10 +141,12 @@ struct blob_t { clear (); _data = static_cast (malloc (size_)); - alloc_assert (_data); + alloc_assert (!size_ || _data); _size = size_; _owned = true; - memcpy (_data, data_, size_); + if (size_ && _data) { + memcpy (_data, data_, size_); + } } // Empties a blob_t.