-3

when i try to run this program with : ./prog_name eventCNT i confront with segmentation fault error while with other argument everything is ok...

    int main(int argc, char *argv[]) {

    printf("Application for up/down/random counter on 7 seg display\n");

    if ( (strcmp(argv[1], "eventCNT") == 0 &&  argc != 2) || (strcmp(argv[1], "eventCNT") != 0 &&  argc != 3) )

    {

        printf( "usage: %s <direction or event counting> <delay>\n", argv[0] );
        printf( "valid direction : up, down, updown, random\n");
        printf( "valid event counting : eventCNT\n");
        printf ("recommended delay range in ms : 0 to 1000\n");
    }
    else
    {
        .
       .
       .  

    }
}
Samuel
  • 6,126
  • 35
  • 70
darkgray
  • 1
  • 2
  • couldn't reproduce. when I run this with a single command line argument it works fine – user2717954 Dec 23 '19 at 08:24
  • Read [*How to debug small programs*](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – Basile Starynkevitch Dec 23 '19 at 08:31
  • 1
    In addition to the problems with checking `argc` and accessing `argv` already mentioned, it seems that the code you've left out (the `else` clause) is what's causing the segfault because that's what executing when you run `./prog_name eventCNT`. – Michael Burr Dec 23 '19 at 08:44
  • 1
    This kind of a problem should nearly always have a [mcve]. That way you don't accidentally leave out relevant code and waste the time of other people. – hyde Dec 23 '19 at 15:26

2 Answers2

2

You should check argc before accessing argv

If argc == 1 and you are accessing argv[1] first, you are accessing invalid memory because argv only has one member, which is argv[0]

C++ evaluates statements from left to right, therefore having undefined behaviour first and then checking whether it was ok to do this is not the best way. Invert the checks to argc and argv

Actually you should write code in a more defensive way like

if (argc < 2)
{
   // Error, not enough arguments
   return -1
}

// From here you know that argv[1] will be a valid string to something and you can freely get `argv[1]`
Samuel
  • 6,126
  • 35
  • 70
  • but i ran this program with 2 arguments (./prog_name eventCNT) and receive this error – darkgray Dec 23 '19 at 10:40
  • If this does not solve your issue please follow this guide: https://stackoverflow.com/help/minimal-reproducible-example – Samuel Dec 23 '19 at 11:58
1

You should use

if (argc >= 2 && strcmp(argv[1], "eventCNT") == 0)

not

if (strcmp(argv[1], "eventCNT") == 0 && argc != 2)

Because if arguments are less than 2, argv[1] is not defined, will point to a random memory address. Therefore a segmentation fault occurs.

Also strcmp has undefined behavior if you points to something not a null-terminated string. see strcmp here

Dia
  • 851
  • 1
  • 15
  • 35