我正在编写如下的加密和解密功能:
encrypt("string") -> "encryptedString"
decrypt("encryptedString") -> "string"
但是,运行它们时我得到的结果很奇怪。
在我的示例中,我正在加密ab#z,A1BZ
以获取:bc#a,Z1AY
,反之亦然(解密)
运行代码时,得到以下输出:
Question 3a (encrypt): bc#a,Z1AY
Question 3b (decrypt): ab#z,A1BZcuments�v�j�
我想强调一下,该功能似乎在正确地完成其工作。请注意,ab#z,A1BZ
是解密输出的一部分。那部分是正确的。但是,其后是cuments�v�j�
[decrypt("bc#a,Z1AY")
应该只导致ab#z,A1BZ
以下是功能:
char* encrypt(const char* plaintext){
char* ciphertext = malloc((strlen(plaintext) + 1) * sizeof(char));
for (int i = 0; i < strlen(plaintext); i++){
if (islower(plaintext[i])){
char c;
if (plaintext[i] == 'z'){
c = 'a';
}
else {
c = plaintext[i] + 1;
}
ciphertext[i] = c;
}
else if (isupper(plaintext[i])){
char c;
if (plaintext[i] == 'A'){
c = 'Z';
}
else {
c = plaintext[i] - 1;
}
ciphertext[i] = c;
}
else {
ciphertext[i] = plaintext[i];
}
}
return ciphertext;
}
char* decrypt(const char* ciphertext){
char* plaintext = malloc((strlen(ciphertext) + 1) * sizeof(char));
for (int i = 0; i < strlen(ciphertext); i++){
if (islower(ciphertext[i])){
char c;
if (ciphertext[i] == 'a'){
c = 'z';
}
else {
c = ciphertext[i] - 1;
}
plaintext[i] = c;
}
else if (isupper(ciphertext[i])){
char c;
if (ciphertext[i] == 'Z'){
c = 'A';
}
else {
c = ciphertext[i] + 1;
}
plaintext[i] = c;
}
else {
plaintext[i] = ciphertext[i];
}
}
return plaintext;
}
这是呼叫/驱动程序代码:
char* ciphertext = encrypt("ab#z,A1BZ");
char* plaintext = decrypt(ciphertext);
printf("Question 3a (encrypt): %s\n", ciphertext);
printf("Question 3b (decrypt): %s\n", plaintext);
free(ciphertext);
free(plaintext);
[SIZE
定义为8的地方
C中的字符串为null-terminated。函数,例如printf()
,期望在字符串的末尾有一个空字节,该字节为零值的字节。
dynamically allocate memory in C时,由操作系统分配。调用malloc()
(而不是calloc()
)时,您无法保证接收到该存储器后的内容。这就是您的代码具有未定义行为的原因-当系统返回的内存恰好以0
作为最后一个字节时,您的代码将运行良好。如果还有其他问题,printf()
将继续写入输出。
您应解决此问题,并将字符串的最后一个字节显式设置为0
。
[其他选择,这被认为是安全的做法,总是将您使用memset()
收到的内存清零:
#include <string.h>
// plaintext is a pointer to a char array
memset(plaintext, 0, sizeof(plaintext));