【问题标题】:stack around variable corrupted堆栈周围的变量损坏
【发布时间】:2013-07-28 13:41:27
【问题描述】:

它因调试错误而崩溃,并说变量“代码”周围的堆栈已损坏。这是我正在做的汉明代码实验室的代码。输入文件只是同一行上的一堆 1 和 0。为什么会崩溃?

void processFile(FILE* read, char* InMessage) {
    int i = 0, count = 0;

    for (i = 0; !feof(read); i++) {
            InMessage[i] = fgetc(read);
        count++;
    }

    InMessage[count] = '\0';
}

void hammingCode(char* InMessage) {
    int len = strlen(InMessage), i = 0, j = 0;
    char code[12], temp[1000];

    temp[0] = '\0';

    for (i = 0, j = 0; i < len; i++, j++) {
        code[j] = InMessage[i];
        if (j == 10) {
            j = 0;

            decode(code);
            code[11] = '\0';
            strcat_s(temp, sizeof(char)*1000, code);
        }
    }

    strcpy_s(InMessage, sizeof(char)*1000, temp);
}

void decode(char* codeWord) {
    int i = 0, j = 0, parity[4] = {0}, diffParity[4] = {0}, twoPower = 0, readNSkip =     0, bitSum = 0;

    for (i = 0; i < 4; i++) {
        twoPower = (int)pow((double)2, i);

        for (j = twoPower; j <= 12; j++) {
            if (readNSkip <= twoPower) {
                if (j != twoPower)  {
                    parity[i] += codeWord[j-2] - 48;
                }
                readNSkip++;
            }
            else {
                if (readNSkip == twoPower*2)
                    readNSkip = 0;
                readNSkip++;
            }
        }

        if (parity[i] % 2 == 0)
            parity[i] = 0;
        else
            parity[i] = 1;

        if ((codeWord[twoPower-1] - 48) != parity[i])
            diffParity[i] = 1;
    }

    for (i = 0; i < 4; i++) {
        twoPower = (int)pow((double)2, i);
        bitSum += diffParity[i]*twoPower;
    }

    codeWord[bitSum] = !codeWord[bitSum];

}

【问题讨论】:

  • 在调试器中运行代码会发生什么?
  • 试试 gdb ./a.out 然后输入 r 回车看看为什么会崩溃..然后修复它!

标签: c stack hamming-code stack-corruption


【解决方案1】:

我在这里看到两个问题:

  1. 在我看来,您在 hammingCode 函数中错误地计算了 InMessage 缓冲区的大小:

    int len = strlen(InMessage), i = 0, j = 0;
    

    strlen 函数通过查找第一个空终止符的位置来确定字符串的长度。如果InMessage 没有被清除,那么这可能会给你一些奇怪的长度,因为它将包含一个随机的字节序列。相反,如果您已清除缓冲区,则 len 将为 0。

    为了克服这个问题,调用者最好提供缓冲区的大小:

    int hammingCode (char *InMessage, size_t messageSize)
    

    并使用messageSize 代替len

    建议对其他两个函数使用相同的策略,因为目前提供的缓冲区可能会溢出。

  2. 继上一个问题之后,decode 函数可能正在缓冲区边界之外写入。将缓冲区的长度提供给 decode 并添加适当的检查以确保函数不会写入给定的范围之外是个好主意。

【讨论】:

    猜你喜欢
    • 2018-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-28
    • 2012-11-08
    • 2019-09-04
    • 2020-07-26
    相关资源
    最近更新 更多