简体   繁体   中英

Why is this for loop infinitely looping? (C)

This is really strange. This program was working fine on another computer, but when I try it on this one it runs forever. Also it is a for loop, which adds even more to my confusion. SIZE_OF_DATA is a preprocessor variable, which I think might be causing the problem.. But I don't know. When I add a printf, it shows only one iteration of the outside loop and is looping infinitely in the inner loop. I have no idea why.

for(i=0; i<size; i++){
    for(j=0;j<SIZE_OF_DATA; j++){
      aArray[i*SIZE_OF_DATA + j] = aPointer[i]->b[j]; 
      cArray[i*SIZE_OF_DATA + j] = 0;                            
      dArray[i*SIZE_OF_DATA + j] = i*SIZE_OF_DATA + j;
      if (i==0)
        eArray[j] = 0;
    }
  }

I'm worried that I somehow destroyed my program... But I have barely done anything but add comments!

This:

aArray[i*SIZE_OF_DATA + j]

looks like you might be writing outside the array ( cArray and dArray too) in the last iteration. Are you sure you're getting a correct index into the array? If not, through the wonders of undefined behavior, you are probably writing to memory that belongs to other variables, including i and j , which could make this loop go on forever.

Buggy programs with undefined behavior behave very... undefined. Though without seeing more code, no one can be sure.

My approach to debugging this piece of code would be to print the values i and j in the for loop. Perhaps SIZE_OF_DATA increases unintentionally in some block of your code although this shouldn't matter.

尝试将i * SIZE_OF_DATA + j设置为变量,这可能就是您的问题所在。

Can you please mention the data type of 'j'. I assume that if suppose the data type of 'j' is char and your value of 'SIZE_OF_DATA' macro is some thing like 150. then the value of 'j' will be iterated between -128 to 127. So it will run infinitely

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM