Sir2B
Sir2B

Reputation: 1079

Why is GCC complaining with Wstringop-overflow?

I have code which looks like this:

char* newChar = new char[strlen(inputCharArray)+1];
if (NULL == newChar) {
    return;
}
strncpy(newChar, inputCharArray, strlen(inputCharArray));
newChar[strlen(inputCharArray)] = '\0';

This seems for me like totally valid code. But GCC 9.2.1 is complaining about it, with the following warning:

warning: 'char* strncpy(char*, const char*, size_t)' specified bound depends on the length of the source argument [-Wstringop-overflow=]

Upvotes: 1

Views: 638

Answers (1)

mirabilos
mirabilos

Reputation: 5347

Yes, GCC is a bit weird about this. But this actually does point out a sense and performance problem in your code. If you use the function appropriate for when you know the source string length, it will get much faster and avoid the warning:

size_t inputCharArrayLen = strlen(inputCharArray) + 1U;
char* newChar = new char[inputCharArrayLen];
if (NULL == newChar) {
    return;
}
memcpy(newChar, inputCharArray, inputCharArrayLen);

(This also avoids possibly running strlen twice.)

Upvotes: 1

Related Questions