0

I have spent 5 hours on this and I am still having no idea what segmentation fault it is. Can you please help?

Here is the code that I have written:

string t = GetString();
int y = strlen(t);
int g = 0;
string s = argv[1];
for (int i=0; i<y; i++)
{
    if (isalpha(t[i]))
    {
        int f = g % z;
        if (isupper(t[i]))
        {
            if (isupper(argv[f]))
            {
                int h=(t[i]-97+s[f]-97)%26 + 97;
                printf("%c", h);
            }
            else
            {
                int h=(t[i]-97+s[f]-65)%26 + 97;
                printf("%c", h);
            }
        }
        else
        {
            if (isupper(argv[f]))
            {
                int h=(t[i]-65+s[f]-97)%26 + 65;
                printf("%c", h);
            }
            else
            {
                int h=(t[i]-65+s[f]-65)%26 + 65;
                printf("%c", h);
            }
        }
    g++;
    }
    else
    {
        printf("%c", t[i]);   
    }
}
printf("\n");

}

1
  • Having the same issue. Probably, error occurs in line: string s = argv[1]; I have not yet figure it out how to solve. As soon as I get it done, I'll let you know. – Marcello Scattolini Dec 4 '16 at 11:06
1

Your seg fault comes from this: if (isupper(argv[f])). The isupper() function takes a single character. argv[f] is either going to be a string, or not exist, depending on the value of f. Since f starts at 0, it's the name of the program called in the command line, or ./vigenere. Either way, it's going to cause a segmentation fault.

The more serious issue is why you are using argv[f]. If you were trying to access a particular character in the key that was given as the first parameter in the command line, it would look more like argv[1][f], or more simply, s[f].

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

0

To understand segmentation faults fully, I suggest re-reading lectures notes to/re-watching the lectures for Week 2.

Here is the simple definition from Week 2's first lecture:

A segmentation fault means we touched a segment of memory that doesn’t belong to us.

For example, look at this line: argv[f]. You probably mean something like argv[1][f]. With two command-line arguments, you can only use argv[0] and argv[1], and if f ever gets to be greater than 1 in your current implementation, a segmentation fault will occur. (You only need to worry about iterating through argv[1] here, so think about how to do that properly based on the rules of a vigenere cipher, which I'm assuming you're working on since you have string s = argv[1];.)

Also, it would be worthwhile to watch the short on GDB from Week 4. Use this tool (along with printf if necessary) to identify precisely when and where the segfault occurs.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .