user3713232 user3713232 - 3 months ago 18
C Question

Command line argument Segmentation fault (core dumped)

I understand that a segmentation fault means I'm trying to use memory I shouldn't be touching, but I can't figure out where it's coming from in my code. I wrote a program for an assignment that uses vigenere's cipher to encipher some plain text. It compiles fine but when I run it with a command line argument I get a segmentation fault.

#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>

int main(int argc, string argv[])
{
// check to make sure the user entered a key
if(argc != 2)
{
printf("You need to enter a key, and only one. Please enter an alphabetical key. \nSyntax: ./vigenere key \n");
exit (1);
}

// check to make sure the key is alphabetical
string k = argv[1];
if(isalpha(k) == false)
{
printf("Pleas enter an alphabetical key.\n");
exit (2);
}
// Get a string of plaintext
printf("Please enter your secret messege.\n");
string p = GetString();
// Encipher
int lk = strlen(k);
int lp = strlen(p);
for(int i = 0, j = 0; i < lp; i++, j++)
{
if(isupper(k[j]))
{
tolower(k[j]);
}
if(j > lk)
{
j = 0;
}
if(isalpha(p[i]))
{
if (islower(p[i]))
{
printf("%c", ((((p[i] - 97) + (k[j] - 97)) %26) +97));
}
else
{
printf("%c", ((((p[i] - 65) + (k[j] - 97)) %26) +65));
}
}
else
{
printf("%c", p[i]);
}
}
printf("\n");
return 0;
}

Answer

This code looks suspicious:

if(isupper(k[j]))
    {
        tolower(k[j]);
    }
    if(j > lk)
    {
        j = 0;
    }

You use k[j] but the check afterwards suggests that j could be greater than lk. So k[j] could be out of bounds.