c - 如何在这个简单的加密程序中修复分段错误?
问题描述
在多次尝试编写这个程序后,我完全从我正在阅读的书中复制了这个。我继续收到相同的分段错误错误。
调试器说“无法访问地址 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
解决方案
在提示用户输入您正在执行的字符串的选项 1 和 2 中:
scanf("%s", &iSelection);
这显然是错误的,因为iSelection
变量是 anint
但"%s"
格式说明符需要一个字符串。我认为您打算这样做:
scanf("%s", myString);
推荐阅读
- python - 从大型歌手中寻找最佳匹配词
- node.js - Puppeteer 不会提取所有元素
- kotlin - 如何在 Kotlin 中获取 lambda/函数签名?
- mysql - MySql 查询优化器
- javascript - react native:如何使用导航 5 清除状态?
- php - 我的订单列表 Laravel 8 中的图像路径问题
- uuid - 覆盖 DICOM 中的像素数据时应替换哪些 DICOM UID?
- mysql - 如何在数据库上的 WordPress 的 ACF 字段中插入数据
- angular - 如何添加单元测试用例以订阅角度?
- templates - 使用 org-capture 在目录中创建新的文本文件