0

I have three questions,

  1. What will happen we pass -1 as value for 3rd parameter in strncmp() ie. n number bytes of bytes to compare?
  2. Why the output differs in ARM and PPC? ie. if which one correct?
  3. If I use memcmp instead of strncmp, I m getting "inside else" output in both ARM and PPC. How and why?

    char str[10];
    
    memset(str,'\0',sizeof(str));
    
    printf("str:%s ,len:%d\n\r",str,strlen(str));
    
    if(strncmp(str,"Maximum",(strlen(str)-1)) == 0)    
    {         
        printf("inside if\n\r");     
    }   
    else    
    {    
        printf("inside else\n\r");    
    }
    

Output in ppc

str: ,len:0
inside else

Output in arm

str: ,len:0
inside if
artless noise
  • 21,212
  • 6
  • 68
  • 105
Harini
  • 13
  • 1
  • 3
    The third argument to `strncmp()` is of type `size_t`, which is unsigned. – EOF Jul 31 '15 at 10:29
  • Since one of the strings is empty, you're comparing 0 characters from one against 0 characters from the other regardless of the limit (but without the guarantee of equality that you'd have if the _limit_ was 0). – Notlikethat Jul 31 '15 at 10:54
  • What don't you understand what is not descibed in the both functions' documenation? http://man7.org/linux/man-pages/man3/strcmp.3.html http://man7.org/linux/man-pages/man3/memcmp.3.html – alk Jul 31 '15 at 10:56
  • `strlen(str)-1` mostly ever is a route into to desaster. What do expect this to return for a "string" of length 0? http://man7.org/linux/man-pages/man3/strlen.3.html – alk Jul 31 '15 at 10:58
  • What's with the recent fascinatinon for doing obviously stupid things and asking which particular brad of stupid ensues? 'which one correct' - are you kidding me??? – Martin James Jul 31 '15 at 11:21
  • 2
    I'm voting to close this question as off-topic because it's another 'I drove my car into a tree, why am I in hospital?' question. – Martin James Jul 31 '15 at 11:22

1 Answers1

0

What will happen we pass -1 as value for 3rd parameter in strncmp()

Assuming the 3rd parameter is defined a being of size_tand furthermore assuming size_t is defined as unsigned integer, passing in -1 will result in a "wrap-around" and the function will receiving the value of SIZE_MAX. On a 32bit system this probably would be 0xffffffff.

alk
  • 69,737
  • 10
  • 105
  • 255