如何解决使用Caesar密码对邮件进行加密的程序
我的代码中一直存在此错误。它工作正常,但在plaintext
中输入的第8个字符之后立即出现,就像公式出错或计算中发生了一些变化,并开始加密成错误的字符。
请有人帮我弄清楚我做错了什么吗?
我已经尝试使用调试器,但是我不明白发生了什么问题。
#include <stdio.h>
#include <cs50.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
char upperciphertext (char text);
char lowerciphertext(char text);
int key;
char cyphertext[] = "ciphertext: ";
int main(int argc,string argv[])
{
//check if command line arg. is inputed and not more than 1
if (argc > 2 || argc < 2)
{
printf("Usage: ./caesar key\n");
return 1;
}
//check if characters are digits
for (int i = 0; argv[1][i] != '\0'; i++)
{
if (isdigit(argv[1][i]))
{
//convert commandline argument to int
}
else
{
printf("Usage: ./caesar key\n");
return 1;
}
}
key = atoi(argv[1]);
char * plaintext = get_string("plaintext: \n");
//loop to iterate over each character in text
for (int i=0; plaintext[i] != '\0'; i++)
{
//turn uppercase letters to uppercase ciphertext
if (isalpha(plaintext[i]) && isupper(plaintext[i]))
{
char cytext = upperciphertext(plaintext[i]);
strncat(cyphertext,&cytext,1);
}
//turn lowercase letters to lowercase ciphertext
else if (isalpha(plaintext[i]) && islower(plaintext[i]))
{
char lowcytext = lowerciphertext(plaintext[i]);
strncat(cyphertext,&lowcytext,1);
}
else
{
strncat(cyphertext,&plaintext[i],1);
}
}
printf("%s\n",cyphertext);
}
//function to cipher uppercase characters
char upperciphertext (char text)
{
int alphaindex,cipher,ciphertext;
char ctext;
alphaindex = text - 65;
cipher = (alphaindex + key) % 26;
ciphertext = cipher + 65;
ctext = ciphertext;
return ctext;
}
//function to cipher lowercase characters
char lowerciphertext(char text)
{
int alphaindex,ciphertext;
char ctext;
alphaindex = text - 97;
cipher = (alphaindex + key) % 26;
ciphertext = cipher + 97;
ctext = ciphertext;
return ctext;
}
解决方法
char cyphertext[] = "ciphertext: ";
将cyphertext
定义为足以容纳"ciphertext: "
的大小,并且strncat
附加到末尾但不增加分配的空间。因此,您的程序会在为数组分配的空间之外进行写操作,从而破坏用于其他目的的内存。
您必须为strncat
提供足够的存储空间,以便可以附加字符。增大数组或使用其他分配的缓冲区来工作。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。