我知道分段错误意味着我正在尝试使用我不应该触摸的内存,但我无法弄清楚它在我的代码中来自哪里。我为一个作业编写了一个程序,该程序使用 vigenere 的密码来加密一些纯文本。它编译得很好,但是当我使用命令行参数运行它时,我得到一个分段错误。
#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;
}