2015-07-04 73 views
1

因此,我试图从.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 
} 

如果你能帮助我了解为什么发生这种情况,我将不胜感激。

+1

似乎未定义的行为案例。什么是“记忆”? – haccks

+3

'l'未初始化。和'我'需要重置。 – BLUEPIXY

回答

1

你的代码是未定义行为,它只能侥幸:

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()代替。

+0

谢谢,现在完美! – Cody

+0

@Cody很高兴能帮到你。像这样的奇怪问题(“当我删除这个变量,代码崩溃”)通常意味着其他的东西是错误的,并且在某处存在UB。 –