Reputation: 5186
#include <string.h>
void test(char charArray [100])
{
strncpy(charArray, "some text", sizeof(charArray));
}
int main()
{
char charArray [100];
test(charArray);
// EDIT: According to comment from P0W I added this line - where is the difference?
strncpy(charArray, "some text", sizeof(charArray)); // compiles OK
}
Compiled with gcc 4.9.2 on SLES 11 SP2 with this command line g++ gcc-warning-bug-2.cpp -Wall -Wextra -c -Werror
I get this warning. Due the -Werror
flag I cannot compile the project:
gcc-warning-bug-2.cpp: In function ‘void test(char*)’:
gcc-warning-bug-2.cpp:5:40: error: argument to ‘sizeof’ in ‘char* strncpy(char*, const char*, size_t)’ call is the same expression as the destination; did you mean to provide an explicit length? [-Werror=sizeof-pointer-memaccess]
strncpy(charArray, "some text", sizeof(charArray));
^
cc1plus: all warnings being treated as errors
According to the actual gcc 4.9.2 documentation https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html
-Wsizeof-pointer-memaccess
Warn for suspicious length parameters to certain string and memory built-in functions if the argument uses sizeof.
This warning warns e.g. about memset (ptr, 0, sizeof (ptr)); if ptr is not an array, but a pointer, and suggests a possible fix, or about memcpy (&foo, ptr, sizeof (&foo));. This warning is enabled by -Wall.
this should be compiled fine because charArray
is an array!
Bug? Should I report it to GNU gcc developer team?
Upvotes: 3
Views: 5871
Reputation: 52538
You fell straight into the trap.
In C, C++, Objective-C, Objective-C++, a parameter with a declaration that looks like "array of T" actually has type T*.
Your parameter charArray has a declaration that looks like "array of 100 chars", but the declaration is in fact "pointer to char".
Therefore, your third parameter to strncpy has a value of (most likely) 4 or 8, and not the 100 that you seem to expecct.
BTW. strncpy is highly dangerous the way you use it.
Upvotes: 11