Skip to content

Commit 62e83b3

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 51e09d0 commit 62e83b3

File tree

3 files changed

+25
-1
lines changed

3 files changed

+25
-1
lines changed

src/util-inl.h

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

235235
// As per spec realloc behaves like malloc if passed nullptr.
236236
void* Malloc(size_t size) {
237+
if (size == 0) size = 1;
237238
return Realloc(nullptr, size);
238239
}
239240

240241
void* Calloc(size_t n, size_t size) {
241-
if ((n == 0) || (size == 0)) return nullptr;
242+
if (n == 0) n = 1;
243+
if (size == 0) size = 1;
242244
CHECK_GE(n * size, n); // Overflow guard.
243245
return calloc(n, size);
244246
}

test/cctest/util.cc

+14
Original file line numberDiff line numberDiff line change
@@ -74,3 +74,17 @@ TEST(UtilTest, ToLower) {
7474
EXPECT_EQ('a', ToLower('a'));
7575
EXPECT_EQ('a', ToLower('A'));
7676
}
77+
78+
TEST(UtilTest, Malloc) {
79+
using node::Malloc;
80+
EXPECT_NE(nullptr, Malloc(0));
81+
EXPECT_NE(nullptr, Malloc(1));
82+
}
83+
84+
TEST(UtilTest, Calloc) {
85+
using node::Calloc;
86+
EXPECT_NE(nullptr, Calloc(0, 0));
87+
EXPECT_NE(nullptr, Calloc(1, 0));
88+
EXPECT_NE(nullptr, Calloc(0, 1));
89+
EXPECT_NE(nullptr, Calloc(1, 1));
90+
}

test/parallel/test-crypto-pbkdf2.js

+8
Original file line numberDiff line numberDiff line change
@@ -79,3 +79,11 @@ assert.throws(function() {
7979
assert.throws(function() {
8080
crypto.pbkdf2('password', 'salt', 1, -1, common.fail);
8181
}, /Bad key length/);
82+
83+
// Should not get FATAL ERROR with empty password and salt
84+
// https://github.com/nodejs/node/issues/8571
85+
assert.doesNotThrow(() => {
86+
crypto.pbkdf2('', '', 1, 32, 'sha256', common.mustCall((e) => {
87+
assert.ifError(e);
88+
}));
89+
});

0 commit comments

Comments
 (0)