简体   繁体   中英

segmentation fault when using argv[1]

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

    }
}

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]`

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM