Search code examples
cevaluationstrcmpargssequence-points

Segfault with strcmp


I am using strcmp in following ways

  1. Passing char[] array names
  2. Passing pointers to string literals but, the second result in seg fault. even though i have confirmed that pointers point to correct string literals, i am confused as to why i am getting seg fault.. Here is the code:-

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main(int argc, char const *args[])
    {
      char firstName[strlen(*++args)];
      strcpy(firstName, *args);
      char lastName[strlen(*++args)];
      strcpy(lastName, *args);
      printf("%s\t%s\n", firstName, lastName);
    
      printf("%d\n", strcmp(firstName, lastName));// this works
    
      printf("%d\n", strcmp(*(--args),*(++args)));//this gives me a seg fault
    
      return EXIT_SUCCESS;
    }
    

I am saving it as str.c and when i compile it, first i get following warning:

[Neutron@Discovery examples]$ gcc -Wall str.c -o str

str.c: In function ‘main’:
str.c:15: warning: operation on ‘args’ may be undefined

finally running it, gives a seg fault as shown below

[Neutron@Discovery examples]$ ./str Jimmy Neutron


Jimmy   Neutron

-4

Segmentation fault (core dumped)

Solution

  • Don't use -- and ++ when you pass the same variable to the same function twice as two different parameters.

    Instead of printf("%d\n", strcmp(*(--args),*(++args)));

    do

    char *first = *(--args);
    char *second = *(++args);
    printf("%d\n", strcmp(first,second));
    

    Still not really readable (better use indexes and check against argc for validity), but at least you don't change the value and evaluate multiple times it at the same sequence point.