cstring-comparisonstrncmp

Comparing N bytes in string


I want to compare argv[1] and the string "pid", but I want to put restrict how much bytes to be compared. I used strncmp, but there are problem, if I put on third argument 3 it compares more than 3 bytes.

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]){
    if (argc < 2)
        exit(EXIT_FAILURE);
    size_t i = 3;
    if (strncmp(argv[1], "pid", i) == 0){
        printf("%ld\n", (long)getpid());
    }

}

in the terminal

   $./main pid
   343
   $ ./main pidd
   354
   $ ./main piddd
   352

Solution

  • strncmp() compares three bytes in all of your three calls. But because it only compares 3 bytes, you can't tell whether the argv[0] string ends after 3 characters or not.

    If you want "pid" not to maych piddddd, try comparing 4 bytes, so that you hit the end-of-string marker ('\0').