Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GCC: Specified bound depends on the length of the source argument

Tags:

c++

gcc

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.

like image 713
user3586940 Avatar asked Jun 26 '19 23:06

user3586940


2 Answers

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.

like image 71
TonyK Avatar answered Nov 15 '22 07:11

TonyK


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.

like image 2
user1261695 Avatar answered Nov 15 '22 06:11

user1261695