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

Deleting unused variable causes code to crash

所以我正在尝试将 .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() 可能 return 如果过早达到 EOF,则无需将换行符写入缓冲区。所以你至少应该在你的循环中考虑到这一点。此外,您永远不会将 i 重置为 0,您应该这样做。改变这个:

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

    }

至:

    i = 0;
    while(instring[i] != '\n' && instring[i] != '[=11=]') // 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()