0

I am following along the cs50 course using Xcode and I have vigenere almost working except it only lets me input 28 characters for the message, beyond that I get "exc bad access" error in Xcode or segmentation fault in terminal.

Int C is a counter for the key and KL is the key length.

int main(int argc, char* argv[])
{
atoi(argv[1]);
string  k = (argv[1]);
printf("Now enter the message.\n");
string p = GetString();
// turn the key string into an array of integers
int key[strlen(k)];
for (int j = 0; j < strlen(k); j++)
  {
    key[j] = ((char)k[j] - 96);
  }

int c = 0;
int kl = strlen(k);

for (int i  = 0; i < strlen(p); i++)
  {
    // make the key rollover
    if (c > kl - 1)
    { key[c] = (key[c % kl]); } 

the encryption starts on this line checking for lower case letter

    if ((char)p[i] > 96 && (char)p[i] < 123)
    {

the error says it happens on this line:

        lower(p, i, key, c);
        c ++;
    }
    else if ((char)p[i] > 64 && (char)p[i] < 91)
    {
        upper(p, i, key, c);
        c ++;
    }

    printf("%c", (p[i]));
  }

}

void lower( string p, int i, int k[], int c)
{

the error happens specifically while executing this line:

if (((char)p[i] + k[c]) < 123)
{p[i] = (char) (p[i] + k[c]);}

else if (((char)p[i]) + k[c] > 122)
{p[i] = ((char) (((p[i]) + k[c])% 122) + 96);}
}

upper does the same as lower but with uppercase

It doesn't do this when I try to put a message in the Caesar cipher which this is based off, only this one. If anyone could help I would appreciate it as I'm really stuck on this.

1

I'm not entirely sure, but I'm thinking that your problem lies here:

if (c > kl - 1)
{ key[c] = (key[c % kl]); } 

This attempts to do an assignment to an element in key[]. Let's say that kl=5 and c=5, and key was defined as having 5 elements from 0 to 4. That means that you're doing this:

if (5 > 5 - 1)
{ key[5] = (key[0]); } 

This means that you're trying to access an invalid element, key[5].

It looks to me that you're trying to wrap back around on the key. This code doesn't reset the index, it only does an assignment to key[c]. Since c is free to grow without limit, it will cause an attempt to access an element beyond the end of key[]. If my diagnosis is correct, you should be resetting c, not key[c]. This argument applies to all the arrays that are using c as an index, including k[].

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

1
  • That would be it, thanks!
    – Evan
    Feb 27 '16 at 17:25

You must log in to answer this question.

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