为什么使用malloc的加密程序会报堆分配未初始化值错误?
报错翻译
你收到的Valgrind报错中文含义为:
//==820== 堆分配创建的变量存在未初始化的值
问题根因
- 密文字符串缺少终止符
\0:你调用malloc(n + 1)申请了长度为n+1的堆内存,循环逻辑仅为前n位下标赋值,最后1位未做任何初始化操作。C语言字符串以\0作为结束标记,后续printf按%s格式输出密文时,会持续读取内存直到遇到\0,就会访问到未初始化的堆内存区域触发报错。 - 附加风险点:需要确保你的
key字符串长度至少为26位,否则当明文存在大小写字母时,tolower(plaintext[i]) - 97的取值范围是0~25,会出现数组越界访问的问题。
修复方案
在ciphering函数的for循环结束后、return前,补充一行代码为密文设置终止符即可:
ciphertext[n] = '\0';
修复后的完整ciphering函数示例:
char *ciphering(string key, string plaintext) { int n = strlen(plaintext); char *ciphertext = malloc(n + 1); // 判空逻辑可以按需补充,避免malloc失败空指针问题 if (ciphertext == NULL) { return NULL; } for (int i = 0; i < n; i++) { if (isupper(plaintext[i])) ciphertext[i] = toupper(key[(tolower(plaintext[i]) - 97)]); else if (islower(plaintext[i])) ciphertext[i] = tolower(key[(tolower(plaintext[i]) - 97)]); else ciphertext[i] = plaintext[i]; } // 补充字符串终止符 ciphertext[n] = '\0'; return ciphertext; }
内容的提问来源于stack exchange,提问作者Francisco Gutierrez Ramirez
相关产品推荐
相关产品推荐

