Skip to content

Commit

Permalink
fix(blob): allow blob object to be initialized with null-pointer ch…
Browse files Browse the repository at this point in the history
…ar array whose length must be zero (#2110)

Fix #2109.

Null-pointer char array with zero length is allowed to be used to initialize
`blob` object. Use `DCHECK` instead to check if the pointer is valid while
initializing `blob` object.
  • Loading branch information
empiredan committed Sep 6, 2024
1 parent c99cfd6 commit d0e9260
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
4 changes: 3 additions & 1 deletion src/utils/blob.h
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,9 @@ class blob
/// NOTE: this operation is not efficient since it involves a memory copy.
[[nodiscard]] static blob create_from_bytes(const char *s, size_t len)
{
CHECK_NOTNULL(s, "null source pointer would lead to undefined behaviour");
DCHECK(s != nullptr || len == 0,
"null source pointer with non-zero length would lead to "
"undefined behaviour");

std::shared_ptr<char> s_arr(new char[len], std::default_delete<char[]>());
memcpy(s_arr.get(), s, len);
Expand Down
21 changes: 20 additions & 1 deletion src/utils/test/blob_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,25 @@

namespace dsn {

TEST(BlobTest, CreateFromZeroLengthNullptr)
{
const auto &obj = blob::create_from_bytes(nullptr, 0);

EXPECT_EQ(0, obj.length());
EXPECT_EQ(0, obj.size());
}

#ifndef NDEBUG

TEST(BlobTest, CreateFromNonZeroLengthNullptr)
{
ASSERT_DEATH({ const auto &obj = blob::create_from_bytes(nullptr, 1); },
"null source pointer with non-zero length would lead to "
"undefined behaviour");
}

#endif

struct blob_base_case
{
std::string expected_str;
Expand All @@ -32,7 +51,7 @@ struct blob_base_case
class BlobBaseTest : public testing::TestWithParam<blob_base_case>
{
public:
void SetUp() override
BlobBaseTest()
{
const auto &test_case = GetParam();
_expected_str = test_case.expected_str;
Expand Down

0 comments on commit d0e9260

Please sign in to comment.