Skip to content

Commit 5902ba3

Browse files
TrottMyles Borins
authored and
Myles Borins
committed
src: Malloc/Calloc size 0 returns non-null pointer
Change `Malloc()/Calloc()` so that size zero does not return a null pointer, consistent with prior behavior. Fixes: #8571 PR-URL: #8572 Reviewed-By: Anna Henningsen <[email protected]> Reviewed-By: James M Snell <[email protected]> Reviewed-By: Yorkie Liu <[email protected]> Reviewed-By: Michael Dawson <[email protected]>
1 parent f8ad0dc commit 5902ba3

File tree

4 files changed

+26
-2
lines changed

4 files changed

+26
-2
lines changed

src/node_crypto.cc

+1-1
Original file line numberDiff line numberDiff line change
@@ -5368,7 +5368,7 @@ class RandomBytesRequest : public AsyncWrap {
53685368
error_(0),
53695369
size_(size),
53705370
data_(static_cast<char*>(node::Malloc(size))) {
5371-
if (data() == nullptr && size > 0)
5371+
if (data() == nullptr)
53725372
FatalError("node::RandomBytesRequest()", "Out of Memory");
53735373
Wrap(object, this);
53745374
}

src/util-inl.h

+3-1
Original file line numberDiff line numberDiff line change
@@ -246,11 +246,13 @@ void* Realloc(void* pointer, size_t size) {
246246

247247
// As per spec realloc behaves like malloc if passed nullptr.
248248
void* Malloc(size_t size) {
249+
if (size == 0) size = 1;
249250
return Realloc(nullptr, size);
250251
}
251252

252253
void* Calloc(size_t n, size_t size) {
253-
if ((n == 0) || (size == 0)) return nullptr;
254+
if (n == 0) n = 1;
255+
if (size == 0) size = 1;
254256
CHECK_GE(n * size, n); // Overflow guard.
255257
return calloc(n, size);
256258
}

test/cctest/util.cc

+14
Original file line numberDiff line numberDiff line change
@@ -89,3 +89,17 @@ TEST(UtilTest, ToLower) {
8989
EXPECT_EQ('a', ToLower('a'));
9090
EXPECT_EQ('a', ToLower('A'));
9191
}
92+
93+
TEST(UtilTest, Malloc) {
94+
using node::Malloc;
95+
EXPECT_NE(nullptr, Malloc(0));
96+
EXPECT_NE(nullptr, Malloc(1));
97+
}
98+
99+
TEST(UtilTest, Calloc) {
100+
using node::Calloc;
101+
EXPECT_NE(nullptr, Calloc(0, 0));
102+
EXPECT_NE(nullptr, Calloc(1, 0));
103+
EXPECT_NE(nullptr, Calloc(0, 1));
104+
EXPECT_NE(nullptr, Calloc(1, 1));
105+
}

test/parallel/test-crypto-pbkdf2.js

+8
Original file line numberDiff line numberDiff line change
@@ -84,3 +84,11 @@ assert.throws(function() {
8484
assert.throws(function() {
8585
crypto.pbkdf2('password', 'salt', 1, 4073741824, 'sha256', common.fail);
8686
}, /Bad key length/);
87+
88+
// Should not get FATAL ERROR with empty password and salt
89+
// https://github.com/nodejs/node/issues/8571
90+
assert.doesNotThrow(() => {
91+
crypto.pbkdf2('', '', 1, 32, 'sha256', common.mustCall((e) => {
92+
assert.ifError(e);
93+
}));
94+
});

0 commit comments

Comments
 (0)