变量 'ch' 周围的堆栈已损坏

Stack around the variable 'ch' was corrupted

我正在为 Vegenere Variant Cipher 和 运行 编写解密算法以解决一些 C 特定问题(我对 C 不太熟悉)。

我明白了
Run-Time Check Failure #2 - Stack around the variable 'ch' was corrupted”错误。

如果我理解错误的话,当我尝试read/write时ch不可用(ch在这种情况下代表从文本文件中读取的HEX值,我已经发布了下面函数的代码)。

但是,对于我来说,我无法弄清楚它发生在哪里。我在退出函数之前关闭了文件(在我离开函数时抛出异常)。

你能帮我看看哪里错了吗?提前致谢。

P.S。我用 C++ 标记了这个问题,它应该几乎是一样的,除了,也许,我们是如何读入文件的。 无论如何,我的代码如下:

int getKeyLength(char *cipherTxtF){

int potKeyL = 1;
float maxFreq = 0.00;
int winKL = 1;


for (potKeyL = 1; potKeyL <= 13; potKeyL++)// loop that is going through each key size startig at 1 and ending at 13
{
    unsigned char ch;
    FILE *cipherTxtFi;
    cipherTxtFi = fopen(cipherTxtF, "r");
    int fileCharCount = 0;
    int freqCounter[256] = { 0 };
    int nThCharCount = 0;
    while (fscanf(cipherTxtFi, "%02X", &ch) != EOF) {
        if (ch != '\n') {
            if (fileCharCount % potKeyL == 0){
                int asciiInd = (int)ch;
                freqCounter[asciiInd] += 1;
                nThCharCount++;
            }
        }
        fileCharCount++;
    }
    fclose(cipherTxtFi);
    float frequenciesArray[256] = { 0 };
    float sumq_iSq = 0;     
    int k;
    for (k = 0; k < 256; k++){
        frequenciesArray[k] = freqCounter[k] / (float)nThCharCount;
    }

    for (k = 0; k < 256; k++){
        sumq_iSq += frequenciesArray[k] * frequenciesArray[k];
        printf("%f \n", sumq_iSq);
    }

    if (maxFreq < sumq_iSq) {
        maxFreq = sumq_iSq;
        winKL = potKeyL;
    }       
}

return winKL;

}

您正在尝试读取 fscanf() 的十六进制整数(格式为“%02X”,其中 X 表示 "integer in hex format")并将其存储到 char 中。

不幸的是 fscanf() 只收到了字符的地址,不知道您还没有提供 int 的地址。由于 int 大于 char,内存被破坏。

解决方案可以是:

int myhex; 
while (fscanf(cipherTxtFi, "%02X", &myhex) != EOF) {
   ch = myhex; 
   ...