diff --git a/napi-inl.h b/napi-inl.h index 1f6563fea..93cef5958 100644 --- a/napi-inl.h +++ b/napi-inl.h @@ -900,6 +900,11 @@ inline String String::New(napi_env env, const std::u16string& val) { } inline String String::New(napi_env env, const char* val) { + if (val == nullptr) { + NAPI_THROW( + TypeError::New(env, "String::New received a nullpointer as a value"), + Napi::String()); + } napi_value value; napi_status status = napi_create_string_utf8(env, val, std::strlen(val), &value); NAPI_THROW_IF_FAILED(env, status, String()); diff --git a/test/name.cc b/test/name.cc index 3a296ec58..4e56141bc 100644 --- a/test/name.cc +++ b/test/name.cc @@ -82,11 +82,18 @@ Value CheckSymbol(const CallbackInfo& info) { return Boolean::New(info.Env(), info[0].Type() == napi_symbol); } +void AssertErrorThrownWhenPassedNullptr(const CallbackInfo& info) { + const char* nullStr = nullptr; + String::New(info.Env(), nullStr); +} + Object InitName(Env env) { Object exports = Object::New(env); exports["echoString"] = Function::New(env, EchoString); exports["createString"] = Function::New(env, CreateString); + exports["nullStringShouldThrow"] = + Function::New(env, AssertErrorThrownWhenPassedNullptr); exports["checkString"] = Function::New(env, CheckString); exports["createSymbol"] = Function::New(env, CreateSymbol); exports["checkSymbol"] = Function::New(env, CheckSymbol); diff --git a/test/name.js b/test/name.js index 457774690..4c74542f0 100644 --- a/test/name.js +++ b/test/name.js @@ -7,6 +7,11 @@ module.exports = require('./common').runTest(test); function test(binding) { const expected = '123456789'; + + assert.throws(binding.name.nullStringShouldThrow, { + name: 'TypeError', + message: 'String::New received a nullpointer as a value', + }); assert.ok(binding.name.checkString(expected, 'utf8')); assert.ok(binding.name.checkString(expected, 'utf16')); assert.ok(binding.name.checkString(expected.substr(0, 3), 'utf8', 3));