Issue
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.
Solution
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.
Answered By - TonyK Answer Checked By - Terry (WPSolving Volunteer)