0
#include<stdio.h>
#include<cs50.h>
#include<string.h>
#include<stdlib.h>
#include<ctype.h>
int main(int argc,string argv[])
{
printf("%s",argv[1]);
string k=argv[1];
    int j = atoi(k);
printf("%i",j);
printf("%i",argc);

  if(argc == 2)


   {
    printf("plaintext:");
    string s=get_string();
 printf("%c",s[0]+j);
printf("%ld",strlen(s));
printf("ciphertext: ");
    for(int i=0,n=strlen(s);i<n;i++)
    {

        if(isalpha(s[i]))
       {
           if(isupper(s[i]))
           {
        printf("%c",((s[i]+j)%26));

       }
       else
       {
            printf("%c",((s[i]+j)%26));
       }
}

       else
       {
           printf("%c",(s[i]));
       }

    }
}
  else
  {
      printf("invalid\n");
  }

       printf("\n");

   }
1
  • Have you identified which line is causing the seg fault yet? Also, did you resave and recompile your code after making changes to it?
    – Cliff B
    Dec 30, 2017 at 13:43

1 Answer 1

3

Segmentation fault means that you are trying to access a section of memory that you don't have permission to use. This happens when you try to access an index of an array that doesn't exist.

Before you store the second item in argv in the variable k, you should check whether argv actually has two items. You can do this by using the argc variable, which tells you the number of items contained in argv.

You should replace this line:

string k = argv[1];

With this:

// If the number of elements in argv is different than 2
if (argc != 2)
{
    printf("Some error message\n");

    // Exit main with an error code
    return 1;
}

// Now, you know that argv actually has two elements, and you can procede to retrieve the key from it

string k = argv[1];

Let me know if this helps.

You must log in to answer this question.

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