1
votes

I am getting segmentation faults when trying to read command line arguments char-by-char.

I have the following code:

int main(int argc, char** argv)
{
int i,j;
    for(i=1;i<argc;i++)
    {
        for(j=0;argv[i][j]!=0;j++)
        {
             printf("%c",argv[i][j]);
        }
        //printf("%c",argv[i][0]);
    }
}

This code runs, but when I uncomment the line printf("%c",argv[i][0]); I get a segmentation fault. Why exactly is this considered access to unallocated memory and how am I supposed to parse command line arguments without checking their content?

Specifically, I want to know if the argument is of the form: <+->e<0-9A-F> meaning plus or minus followed by 'e' followed by a single hex digit. How would one go about this in c?

1
Please do NOT change the code you're asking about after some (valid!) answers were given. This way you render those answers irrelevant or even erroneous. If you want to enhance your question or narrow it down by presenting a new, but still not working version of your code, add it below the original one or post a new question. - CiaPan
Understood. I am still new to this platform and am still learning how to use it. - MegaFlipFlop

1 Answers

3
votes

The condition for your inner loop is incorrect:

argv[i][j]!="\0"

You're comparing a single char against a string constant. That string constant decays into the address it's stored at, which is what's actually being compared against the elements of the argument string. As a result, because you're not correctly checking for the terminating null byte, you read past the end of the string. Doing so triggers undefined behavior which in your case causes you code to sometimes crash and sometimes not.

What you want here is to check for the value 0:

argv[i][j]!=0