0

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
einpoklum
  • 118,144
  • 57
  • 340
  • 684
Itra
  • 45
  • 10
  • 4
    What makes you think it compares more than 3 bytes? – UnholySheep Apr 27 '19 at 10:46
  • it compares more than 3 bytes ("pid"), I want to compare only 3 characters ("pid"). As you can see terminal output when i enter piddd it executes the if statement – Itra Apr 27 '19 at 10:48
  • so are you trying to so that for the 2nd and 3rd it shouldn't show that result? – P.hunter Apr 27 '19 at 10:48
  • 3
    Yes, it executes the statement because the first 3 characters are the same - you specified it shouldn't compare any characters after that, so `strncmp` returns that they are equal and the `if` evaluates to true. I'm unclear why you claim this proves that it compared more than 3 bytes – UnholySheep Apr 27 '19 at 10:49
  • 2
    Why not use `strcmp` for an *exact* match? This seems to be what you want. – Some programmer dude Apr 27 '19 at 10:53
  • Use strlen() to check the length of your command line argument, then decice if you want to perform the comparison. – nicomp Apr 27 '19 at 10:54
  • Ah yes. I didn't review man page :) – Itra Apr 27 '19 at 10:55
  • the comparison could be: `if( ! strcmp( "pid", argv[1] ) )` – user3629249 Apr 28 '19 at 18:50

3 Answers3

3

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').

einpoklum
  • 118,144
  • 57
  • 340
  • 684
2

This might work:

int i,count=1;
char str[] = "pid";
    for (i = 0;i < 4;i++) 
   {
        if (str[i] != argv[1][i]) 
        {
            count = 0;
            break;
        }
    }
if(count==1)
  printf("%ld\n", (long)getpid());
1

You can have a check like this below:

if ((strlen(argv[1]) <= i) && strncmp(argv[1], "pid", i) == 0){

But for all three possible inputs you tried, the first 3bytes are "pid". So strncmp will obviously returns 0 and is expected only.