C语言替代加密程序逻辑正常但encryptKey无输出、字符串拼接报错
问题修复方案
核心错误原因
- 你把JS的字符串操作习惯带到了C语言中,C的
string本质是char*字符指针,不支持+=直接拼接字符,该操作只会偏移指针地址,不会实现字符串内容拼接 strcat要求两个入参都是以\0结尾的字符串指针,你直接传入单个字符(toupper返回值为int类型的字符值),类型不匹配才会触发对应报错。如果一定要用strcat拼接单个字符,需要先把字符转成长度为1的字符串:
但该方法效率远低于直接给字符数组赋值,不推荐使用。char temp[2] = {0}; temp[0] = toupper(cipher[tempLocation]); strcat(output, temp);- 你当前定义的
string output = ""是只读字符串常量,没有分配可写入的内存空间,即使拼接语法正确也会触发段错误 - 还有几个隐藏逻辑bug:
- 密钥字符合法性判断逻辑写错了,
&&应该改为||,单个字符不可能同时小于a且大于z - 合法性校验的
return 1写在了printf前面,会导致错误提示永远无法输出 - 非字母字符的处理逻辑被包在了
if(lower >= 'a' && lower <= 'z')判断里,会导致原文的数字、符号全部丢失
- 密钥字符合法性判断逻辑写错了,
修复步骤
1. 给输出字符串分配足够内存
加密后的字符串长度和原字符串完全一致,直接分配原字符串长度+1的空间即可(多1位存储字符串结束符\0)
2. 替换+=拼接逻辑,直接给字符数组下标赋值
不需要使用strcat,直接给对应位置赋值即可,性能更高逻辑更清晰
3. 修复密钥校验的逻辑错误
调整判断条件和执行顺序,保证错误提示正常输出
修复后核心代码示例
修复后的encryptKey函数
//encrypt the message string encryptKey(string message) { int len = strlen(message); char* output = malloc(len + 1); if (output == NULL) { printf("Memory allocation failed!\n"); return NULL; } int output_idx = 0; //loop through each character for(int i = 0; i < len; i++) { char lower = tolower(message[i]); if(lower >= 'a' && lower <= 'z') { int tempLocation = lower - 'a'; if(isupper(message[i])) { output[output_idx] = toupper(cipher[tempLocation]); } else { output[output_idx] = tolower(cipher[tempLocation]); } } else { output[output_idx] = message[i]; } output_idx++; } output[output_idx] = '\0'; return output; }
修复后的密钥校验逻辑
//check if the characters are letters only if(tolower(argv[1][i]) < 'a' || tolower(argv[1][i]) > 'z') { printf("All characters should be letters!\n"); return 1; }
可选优化
main函数用完secretMessage后加一行free(secretMessage);,避免内存泄漏。
内容的提问来源于stack exchange,提问作者killerprince182
相关产品推荐
相关产品推荐

