Search code examples
ccross-platformmemcmpstrncmp

What will happen we pass -1 as value for 3rd parameter in strncmp() ie. n number bytes of bytes to compare?


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

Solution

  • 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.