Skip to content

Commit 62e83b3

Browse files
TrottMyles Borins
authored andcommitted
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‎

Lines changed: 3 additions & 1 deletion
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
returnRealloc(nullptr, size);
238239
}
239240

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

‎test/cctest/util.cc‎

Lines changed: 14 additions & 0 deletions
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‎

Lines changed: 8 additions & 0 deletions
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
},/Badkeylength/);
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)