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

如何结合用户输入使用strdup?Polybius密码实现遇阻

Polybius密码解密程序输入处理问题

你的代码存在核心输入存储错误,导致解密逻辑无法正常执行,具体问题和修正方案如下:

原代码问题分析

#include <stdio.h>
#include <string.h>

int main()
{
    
    char cipher[5][5] = {
                    {'a', 'b', 'c', 'd', 'e'},
                    {'f', 'g', 'h', 'i', 'k'},
                    {'l', 'm', 'n', 'o', 'p'},
                    {'q', 'r', 's', 't', 'u'},
                    {'v', 'w', 'x', 'y', 'z'}
                        };
                    
    
    char cm; // 错误:单个char仅能存储1个字符,完全装不下输入的长字符串
    char *original;
    char *portion;
    printf("Enter ciphered message: ");
    scanf("%s", &cm); // 错误:%s需要传入字符数组地址,此处传单个char地址会引发内存溢出


    original = strdup(&cm);
    portion = strtok(original, "-");

    
    while (portion != NULL){

        int i = portion[0]-'0';
        int j = portion[1]-'0';

        printf("%c", cipher[i][j]);
        portion = strtok(NULL, "-");
        
        }
    

    return 0;
}

修正后的代码

#include <stdio.h>
#include <string.h>

int main()
{
    
    char cipher[5][5] = {
                    {'a', 'b', 'c', 'd', 'e'},
                    {'f', 'g', 'h', 'i', 'k'},
                    {'l', 'm', 'n', 'o', 'p'},
                    {'q', 'r', 's', 't', 'u'},
                    {'v', 'w', 'x', 'y', 'z'}
                        };
                    
    
    char cm[100]; // 改为足够大的字符数组,用于存储输入的完整字符串
    char *original;
    char *portion;
    printf("Enter ciphered message: ");
    scanf("%s", cm); // 数组名本身就是首元素地址,无需添加&符号


    original = strdup(cm);
    portion = strtok(original, "-");

    
    while (portion != NULL){

        int i = portion[0]-'0';
        int j = portion[1]-'0';

        printf("%c", cipher[i][j]);
        portion = strtok(NULL, "-");
        
        }
    
    free(original); // 释放strdup在堆上分配的内存,避免内存泄漏

    return 0;
}

关键修正说明

  • 替换单个char cm为字符数组char cm[100]:输入的密码字符串(如00-11-22-33-44)长度远大于1,必须用数组才能完整存储,单个char会导致输入溢出、破坏内存数据。
  • 修改scanf("%s", cm):数组名本身就代表数组首元素的地址,无需加&,加&会导致类型不匹配,同时避免非法内存访问。
  • 新增free(original):strdup会在堆内存中分配空间,使用完毕后手动释放可避免内存泄漏。

现在输入00-11-22-33-44即可正确输出agntz。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 02:40:32