The following code:
while (node)
{
if (node->previous== NULL) break;
struct Node* prevNode = node->previous;
len = strlen(prevNode->entity);
//pp is a char* fyi
pp-=len;
strncpy(pp, prevNode->entity, len+1);
*(--pp) = '/';
node = prevNode;
}
Generates the following warning/error in GCC (I treat all warnings as errors):
../someFile.C:1116:24: error: 'char* strncpy(char*, const char*, size_t)' specified bound depends on the length of the source argument [-Werror=stringop-overflow=]
1116 | strncpy(pp, prevNode->entity, len+1);
| ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
../someFile.C:1114:29: note: length computed here
1114 | len = strlen(prevNode->entity);
| ~~~~~~^~~~~~~~~~~~~~~~~~~~
Why is GCC giving me a warning? What is wrong with relieing on the size of a source argument for the buffer size? Can someone give an example of what issues this may cause? Code does what it should I'm just curious why I'm getting a warning.
The point is that the length bound passed to strncpy
should depend on the size of the destination argument, not the source argument. Otherwise, what is it even for? The compiler correctly recognises that there is no point to using strncpy
here, and gives you an informative error message to that effect.
According the man page,
"The stpncpy() and strncpy() functions copy at most len characters from src into dst. If src is less than len characters long, the remainder of dst is filled with `\0' characters. Otherwise, dst is not terminated."
This has nothing to do with the amount of space in the destination buffer, but rather the number of characters needed to be copied. If one wishes to copy len characters from src into dst and src has more than len characters, then substituting strcpy will not produce the same results. Also, if the dst buffer's size was allocated with the expected size, then strcpy will produce a buffer overflow.
In this case the warning is misleading and should be ignored or silenced.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With