首页 > 解决方案 > 如何在这个简单的加密程序中修复分段错误?

问题描述

在多次尝试编写这个程序后,我完全从我正在阅读的书中复制了这个。我继续收到相同的分段错误错误。

这是本书的第 7 章:指针程序。 https://www.barnesandnoble.com/p/c-programming-for-the-absolute-beginner-michael-vine/1101415261/2678286102503?st=PLA&sid=BNB_DRS_New+Marketplace+Shopping+Textbooks_00000000&2sid=Google_&sourceId=PLGoP211448&gU96B7-iNENE LHaUncLG9FGCb6hq96xniJRdf0InjdEqM7qFs4-ETXXwzURoC3lYQAvD_BwE

调试器说“无法访问地址 0x7ffffffff000 的内存”,即 sMessage[0] 的地址。我不确定为什么我无法访问数组的内容。

最后,请原谅我糟糕的格式。这是我第一次问问题。

    #include <stdio.h>
    #include <stdlib.h>

    // function prototypes
    void encrypt(char [], int);
    void decrypt(char [], int);

    main()
    {

char myString[21] = {'\0'};
int iSelection = 0;
int iRand;

srand(time(NULL));

iRand = (rand() % 4); // random #, 1-4
system("clear");

printf("okay");

while( iSelection != 4) {

    printf("\n\n1\tEncrypt Clear Text");
    printf("\n2\tDecrypt Cipher Text");
    printf("\n3\tGenerate New Key");
    printf("\n4\tQuit");
    printf("\nSelect a Cryptography Option:");
    scanf("%d", &iSelection);
    switch (iSelection) {

        case 1:
        system("clear");
        printf("\nEnter clear text: ");
        scanf("%s", &iSelection);
        encrypt(myString, iRand);
        break;

        case 2:
        system("clear");
        printf("\nEnter cipher text: ");
        scanf("%s", &iSelection);
        encrypt(myString, iRand);
        break;

        case 3:
        system("clear");
        iRand = (rand() % 4); // random #, 1-4
        printf("\nNew Key Generated\n");
        break;
    } // end switch
} // end while loop
    } // end main

    void encrypt(char sMessage[], int random)
    {
int x = 0;

// encrypt the message by shifting each characters ASCII value
while (sMessage[x] != "\0") {
    sMessage[x] += random;
    x++;
} // end while loop
x = 0;
printf("Encrypted message is: ");

// print encrypted messsage
while (sMessage[x] != "\0") {
    printf("%c", sMessage[x]);
    x++;
} // end while loop
    } // end encrypt function

    void decrypt(char sMessage[], int random)
    {
int x=0;
x=0;

// decrypt the message by shifting each characters ASCII value
while (sMessage[x] != '\0') {
    sMessage[x] = sMessage[x] - random;
    x++;
} // end loop

x = 0;
printf("\n Decrypted Message is: ");

// print decrypted message
while (sMessage[x] != '\0') {
printf("%c", sMessage[x]);
x++;

} // end while loop

    } // end decrypt function

标签: carrayspointersencryption

解决方案


在提示用户输入您正在执行的字符串的选项 1 和 2 中:

scanf("%s", &iSelection);

这显然是错误的,因为iSelection变量是 anint"%s"格式说明符需要一个字符串。我认为您打算这样做:

scanf("%s", myString);

推荐阅读