Search code examples
csegmentation-faultstrcmp

C - strcmp segmentation fault 11


Hello I am new to programming in C. I am trying to learn how to use function. My program run well without arguments but when I add argument e.g. select, select row I get segmentation fault 11. Please can you help where is problem, cause I don't have any errors or warning while I am debugging my program. Thank you

#include <stdio.h>
#include <string.h>
int Select(int function)
{
    if (function == 0)
        printf("row");
    else if (function == 1)
        printf("column");
    return 0;
}

int main(int argc, char *argv[])
{
    int i,j,function;
    for (i = 1; i <= argc; i++)
    {
        if (strcmp(argv[i], "--help") == 0)
        {
            printf("Help");
            break;
        }
        else if (strcmp(argv[i], "select") == 0)
        {
            printf("Select");
            for (j = 2; j <= argc; j++)
            {
                if (strcmp(argv[j], "row") == 0)
                {   function = 0;
                    Select(0);
                }
                else if (strcmp(argv[j], "column") == 0)
                {   function = 1;
                    Select(1);
                }
            }
            break;
        }
    }
    return 0;
}

Solution

  • Don't do this:

            for (j = 2; j <= argc; j++)
            {
                if (strcmp(argv[j], "row") == 0)
    

    C has 0-based arrays. Instead do:

            for (j = 2; j < argc; j++)
    

    If argc says there are 2 items, then that means slots [0] and [1]

    Nearly always for loops should go from 0 to N - 1

    Alternatively, you can iterate without argc, since the last slot of the array is NULL.

    while(argv[i] != 0) {
        // do stuff
    
        ++i;
    }