You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

打印字符指针时实际数据前出现乱码——阿尔贝蒂密码实现求助

阿尔贝蒂密码程序乱码问题排查

你的程序输出前出现乱码,是由以下几个内存操作错误导致的:

1. 未初始化的加密字符串数组

局部数组char encryptedMessage[messageSize];在栈上分配时,默认填充随机垃圾值。strncat函数需要目标字符串以'\0'作为结束标志,否则会从内存中随机位置开始追加字符,导致结果前出现乱码。

修复:
初始化数组并预留结束符空间:

char encryptedMessage[messageSize + 1]; // 多1字节存字符串结束符
encryptedMessage[0] = '\0'; // 初始化空字符串,让strncat能正确找到起始位置

2. 数组越界访问

int numArray[25];定义的数组大小为25,但后续循环for(int i = 0; i < 26; ++i)会访问到numArray[25],超出数组边界,破坏内存中的其他数据,引发未定义行为。

修复:
将数组大小改为26:

int numArray[26];

3. 内存分配未预留结束符空间

malloc(sizeof(encryptedMessage))分配的内存大小等于加密字符数,但C字符串需要额外的'\0'标记结束。不预留该位置会导致strcpy和printf越界读取内存,引发乱码或崩溃。

修复:
分配内存时多申请1字节:

char* p1 = malloc(messageSize + 1);

额外优化:替换低效的strncat

每次用strncat追加单个字符效率较低,可直接通过下标赋值,最后手动添加结束符:

// 替换循环内的strncat代码
encryptedMessage[i] = encryptedChar;
// 循环结束后添加结束符
encryptedMessage[messageSize] = '\0';

修正后的核心代码片段

void encrypt_alberti(const char *message,const char *inner_ring, int initialShift,int periodicShift,int periodLength,char **result){
    int numArray[26]; // 修正数组大小
    int count=0;
    int shiftCount=0;
    for(int i = 0; i < 26; ++i) {
        numArray[i]=(i+initialShift)%26;
    }

    int messageSize=getSize(message);
    char encryptedMessage[messageSize + 1]; // 预留结束符空间

    for(int i=0; i<messageSize;i++){
        count++;
        if(periodicShift!=0){
            if(count%periodicShift==0){
                shiftCount++;
            }
        }
        else{
            periodLength=0;
        }
        char toBeEncrypted=message[i];
        int charNumber=letterToNumber(toBeEncrypted);
        int encryptedNum=numArray[(charNumber+(shiftCount*periodLength))%26];
        char encryptedChar=numToChar(encryptedNum);
        // 直接下标赋值替代strncat
        encryptedMessage[i] = encryptedChar;
    }
    encryptedMessage[messageSize] = '\0'; // 添加字符串结束符

    char* p1=malloc(messageSize + 1); // 分配足够内存
    strcpy(p1,encryptedMessage);
    *result=p1;
}

内容的提问来源于stack exchange,提问作者idkDude

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 15:39:21