セグメンテーション違反は、触れてはならないメモリを使用しようとしていることを意味することを理解していますが、コードのどこから来ているのかわかりません。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;
}