c - 删除未使用的变量会导致代码崩溃

标签 c unused-variables

所以我正在尝试将 .s19 文件中的 s-records 加载到内存中,以用于我正在处理的作业及其工作。但是,当我从我的代码中删除一个未使用的数组时,一切都停止工作并崩溃。

未使用的数组是:

char test[65536];

这是我写的加载器:

void loader(FILE * srec)
{
    char instring[SREC_LEN];
    char test[65536]; // This isn't used, but the program crashes without it for some reason
    int i=0;
    int j=0, k,l;
    while (fgets(instring, SREC_LEN, srec) != NULL)
    {

        while(instring[i] != '\n') // Counts the characters in the s-record
        {
            i++;

        }
        j = j+i;
        for(k=0;k<=i;k++) // Puts the records into memory
        {
            memory[l] = instring[k];
            l++;
        }
        l = j;

    }
    #ifdef DEBUG
    printf("MEMORY: %s",memory);
    #endif // DEBUG
}

如果您能帮助我理解为什么会这样,我将不胜感激。

最佳答案

你的代码有未定义的行为,它只能靠运气:

fgets()如果EOF,可能会在不将换行符写入缓冲区的情况下返回过早达到。所以你至少应该在你的循环中考虑到这一点。你也永远不会重置 i到 0,这是你应该做的。改变这个:

    while(instring[i] != '\n') // Counts the characters in the s-record
    {
        i++;

    }

到:

    i = 0;
    while(instring[i] != '\n' && instring[i] != '\0') // Counts the characters in the s-record
    {
        i++;

    }

l从未初始化;你可能在 memory 中写出了界.初始化 l到 0:

int j = 0, k, l = 0;

(我假设 memory 足以容纳所有东西)。

在我看来它也像你想要的那样for(k = 0; k < i; k++)而不是 for(k = 0; k <= i; k++) , 自 i是要复制的字符数。

您可能想使用 memcpy()相反。

关于c - 删除未使用的变量会导致代码崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31225565/

相关文章:

c++ - 如何使用 UNUSED 宏来消除 CONSTEXPR 函数中的警告?

java - 没有未使用变量的静态 block 的替代方案

c++ - 多维数组与平面数组 - 性能比较

冒泡排序变体中的 C 段错误

c - C 中的结构问题

c - 在C中为大程序分配内存

vb.net - 未使用的局部变量 (Visual Studio 2012)

c - 退出 main 时出现段错误

javascript - JavaScript 中未使用函数参数的标准约定

c++ - 增量变量 "never used"?