编码 Vigenère 密码时 c 中的分段错误

segmentation fault in c while coding Vigenère’s cipher

我真的是编码新手,我一直在自学如何使用 EDX.org 编码。这周我一直在学习密码学,我必须创建一个 Vigenère 密码。我写了代码,大部分是正确的。然而,当我编译程序时,它显示了一个分段错误。我一直在试图弄清楚我们为什么会这样,但我完全被困住了。你能看看我的代码并告诉我哪里错了吗?

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


int index(int k, int c); 

int main (int argc, string argv[1])
{
    //check for correct criteria 
    if (argc = 2, isalpha(argv[1]))
    {
        string text = GetString(); 
        string key = argv[1]; //store key word
        int Totalshift = strlen(key); //number of shift for keyword


        int shift = 0; 

        //loops over the whole text
        for (int i = 0, n = strlen(text); i <n; i++ )
        {
            char p= text[i];
            char k = toupper(key[shift]); //Upper case for each character

           if (isupper(p))
            {
               //convert to 0 index
                 p = p - 65; 
                 k = k - 65; 

                int crypt= index (k , p); 

                printf("%c", crypt+65);

                shift= (shift+1) %Totalshift; 
            }
            else if (islower(p))
            {

                p = p - 97; 
                k = k - 65; 

                int crypt= index (k , p); 

                printf("%c", crypt+97);

                shift= (shift+1) %Totalshift; 
            }
            else 
            {
                printf("%c", p);
            }


        }
            printf("\n");
        }




    //error message
    else
    {
        printf("ERROR!\n");
        return 1; 
    }


}

//index function
int index(int k, int p)
{
   return (k+p)% 26; 

}

string

没有。 永远,永远不要隐藏指针。

int main(int argc, char ** argv)

然后:

//check for correct criteria 
if (argc = 2, isalpha(argv[1]))

在这里,您 将值 2 分配给变量(参数在这方面表现得像局部变量),从而破坏了先前的值(其中包含数字给程序的参数)。结果是分配的值,因此 2。然后是 comma operator:您丢弃 2,然后调用 isalpha(argv[1]),这清楚地表明了为什么您 应该始终打开警告 永远不会隐藏指针:

argv[1]char * 类型,因此 指针 指向字符数组(或者,正如我们所知,在这种情况下,字符数组终止'[=19=]',称为 C 字符串 )。由于 isalpha takes an int as parameter 指针 ("the memory address") 的值被隐式转换为(可能非常大)int 值。引用上面link,强调我的:

The c argument is an int, the value of which the application shall ensure is representable as an unsigned char or equal to the value of the macro EOF. If the argument has any other value, the behavior is undefined.

这可能是分段错误的来源。

最后,GetString 对我来说真的很可疑。假设它分配了一些内存(用于它可能从用户那里读取的字符串)......你在哪里释放那块内存?它真的是在分配内存,还是可能返回一个指向具有自动存储持续时间的数组的指针(可以说是一个局部变量)?