1

I am having trouble understanding this compiler warning. My implementation of strncmp works fine but at compile time I am given a warning along the lines of:

tsh.c:87:41: warning: argument to ‘sizeof’ in ‘strncmp’ call is the same expression as the second source; did you mean to provide an explicit length? [-Wsizeof-pointer-memaccess] 
     strncmp(argv[0], builtIns[1], sizeof(builtIns[1]))==0){

where my implementation is something along the lines of:

static const char* builtIns[] = {"string1", "string2", "string3", "string4"};  

void sampleFunction(char *argv[]) { 
if(strncmp(argv[0], builtIns[2], sizeof(builtIns[2]))==0){ 
  ... do something ...
}

Any advice on what the proper implementation of strncmp should be is greatly appreciated!

ryan
  • 153
  • 2
  • 13
  • 2
    `sizeof(builtins[k])` is the size of a pointer, not the length of the string. – molbdnilo Oct 26 '14 at 08:26
  • dohhh... that should have been obvious.. thanks! – ryan Oct 26 '14 at 08:28
  • Just curious - why use `strncmp()` here instead of plain old `strcmp()`? – Michael Burr Oct 26 '14 at 08:28
  • 1
    `sizeof(builtIns[2]) = 4` since `builtIns` is of type `char *`. I'm amazed that your compiler seems to bother about this since it is a valid expression. Try `strlen(builtIns[2])` instead of the sizeof() and your `strncmp` will get the real length of the string... – Lukas Thomsen Oct 26 '14 at 08:32
  • @LukasThomsen Yeah I agree. Now that I understand the issue the fact that the compiler picked up on it is pretty amazing. – ryan Oct 26 '14 at 08:41
  • 1
    @LukasThomsen: It gives a warning because it is quite obviously a bug. Why would a reasonable person compare 4 chars on a 32 bit and 8 chars on a 64 bit system? – gnasher729 Oct 26 '14 at 09:02
  • @LukasThomsen You either have a guaranteed null-terminated string or you don't. If you do, strlen is useless (use plain strcmp instead of strncmp) and if you don't, strlen won't protect you. – n. m. could be an AI Oct 26 '14 at 09:38
  • @gnasher729 The compiler cannot decide if the code is reasonable or not. The compiler has to check if the expressions are correct. It does not know what the value sizeof(..) evaluates to is used for. And since it is an correct expression it shouldn't bother about it... but I agree that the code is not reasonable. – Lukas Thomsen Oct 26 '14 at 10:51
  • @n.m. I didn't know the concrete function of strncmp (since I always use strcmp). I assumed that it is a strcmp which does not bother about the terminating '\0' and therefore needs the length of the string. For giving an easy answer I simply used strlen(..). – Lukas Thomsen Oct 26 '14 at 10:56
  • @LukasThomsen the compiler cannot decide whether the code is reasonable, but it often can make a good guess, and give you a warning. That's what all warnings are. – n. m. could be an AI Oct 26 '14 at 11:55

0 Answers0