Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

n-api: fix warning about size_t compare with int #15508

Closed
wants to merge 4 commits into from
Closed
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/node_api.cc
Original file line number Diff line number Diff line change
Expand Up @@ -920,13 +920,13 @@ NAPI_NO_RETURN void napi_fatal_error(const char* location,
size_t message_len) {
char* location_string = const_cast<char*>(location);
char* message_string = const_cast<char*>(message);
if (location_len != -1) {
if (static_cast<int>(location_len) != -1) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

size_t might allow for larger values than signed ints and we're wrongly casting 2^n-1 to -1 (where n is how big size_t is). If we want to allow -1 here, why don't we change the parameter type? Or could we use 0 instead of -1 to signal that we don't want to set the message_string?

location_string = reinterpret_cast<char*>(
malloc(location_len * sizeof(char) + 1));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Aside: sizeof(char) is 1 by definition and reinterpret_cast is overkill here, static_cast would have sufficed.

What's more, I don't understand why this code makes copies. This function does not return. It seems like completely unneeded complexity.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The reason for doing copy here is to account for strings that are not null terminated.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay, but the other two points still stand. As well, you don't handle nullptr return values. If you use node::Malloc(), that's taken care of.

Or use std::string, that will also stop Coverity from complaining about memory leaks.

strncpy(location_string, location, location_len);
location_string[location_len] = '\0';
}
if (message_len != -1) {
if (static_cast<int>(message_len) != -1) {
message_string = reinterpret_cast<char*>(
malloc(message_len * sizeof(char) + 1));
strncpy(message_string, message, message_len);
Expand Down