Skip to content

Compiler warning -Werror=stringop-truncation fix for error.c#700

Open
sbytnar wants to merge 1 commit intoakheron:masterfrom
sbytnar:master
Open

Compiler warning -Werror=stringop-truncation fix for error.c#700
sbytnar wants to merge 1 commit intoakheron:masterfrom
sbytnar:master

Conversation

@sbytnar
Copy link

@sbytnar sbytnar commented Sep 26, 2024

Hi. This warning is emitted by newer versions of gcc. The project I'm working with treats this particular warning as an error.
The fix below makes the compiler happy.

The full error message emitted looks like this:

| jansson/src/error.c: In function 'jsonp_error_set_source':
| jansson/src/error.c:25:9: error: '__builtin_strncpy' specified bound depends on the length of the source argument [-Werror=stringop-truncation]
|    25 |         strncpy(error->source, source, length + 1);
|       |         ^
| In function 'jsonp_error_set_source',
| jansson/src/error.c:17:6:
| jansson/src/error.c:23:14: note: length computed here
|    23 |     length = strlen(source);
|       |              ^~~~~~~~~~~~~~
| cc1: all warnings being treated as errors

Thank you.
--Steve

…und depends on the length of the source argument [-Werror=stringop-truncation]"
@sbytnar
Copy link
Author

sbytnar commented Sep 26, 2024

This would fix #630

length = strlen(source);
if (length < JSON_ERROR_SOURCE_LENGTH)
strncpy(error->source, source, length + 1);
strncpy(error->source, source, JSON_ERROR_SOURCE_LENGTH);

Choose a reason for hiding this comment

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

Passing JSON_ERROR_SOURCE_LENGTH here seems unnecessary as the length has just been checked. We already know the length of source and have checked it will fit in the output buffer, therefore I think this is better:

         memcpy(error->source, source, length + 1);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants