首页 > 解决方案 > free():无效指针中止(核心转储)cs50

问题描述

我的替换密码有问题,我无法正确判断我的代码功能,但它会在我的密文末尾打印额外的感叹号,这是我代码的重要部分

int keylen = strlen(argv[1]);
string key = argv[1];
printf("ciphertext: ");
for (int i = 0; i < keylen; i++)
{
    //if it is a lower character we remove the value of a
    //to make it the letters start form 0
    if (islower(plaintext[i]))
    {
        int x = plaintext[i] - 'a';
        printf("%c", tolower(key[x]));
    }
    // the same goes here for uppercase
    else if (isupper(plaintext[i]))
    {
        int y = plaintext[i] - 'A';
        printf("%c", toupper(key[y]));
    }
    else
    {
        //if the text is not an alphabet letter print it as it is
       printf("%c", plaintext[i]);
    }
}

这是输出 ~/pset2/substitution/ $ ./subs JTREKYAVOGDXPSNCUIZLFBMWHQ

明文:你好

密文:vkxxn!

然后我尝试在检查大写的 if 语句之后的循环中添加它,如下所示:

else if (isupper(plaintext[i]))
{
    int y = plaintext[i] - 'A';
    printf("%c", toupper(key[y]));
}
    // breaks at \0 to prevent printing garbage values
else if (plaintext[i] = '\0')
{
    break;
}

我得到这个奇怪的错误 ~/pset2/substitution/ $ ./subs JTREKYAVOGDXPSNCUIZLFBMWHQ

明文:你好

密文:vkxxn

free(): 无效指针

中止(核心转储)

对于这个冗长的问题,我深表歉意,并感谢大家的宝贵时间。

标签: ccomputer-sciencecs50edx

解决方案


我找到了导致错误的代码

else if (plaintext[i] = '\0')
{
    break;
}

在这里,我将值分配给 '\0' 而不是通过双等号检查值 ==
是什么导致了该错误

free():无效指针
已中止(核心转储)

再次感谢您的时间


推荐阅读