Andrew B
Andrew B

Reputation: 71

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!

Upvotes: 0

Views: 159

Answers (4)

Sankar Mani
Sankar Mani

Reputation: 178

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

Upvotes: 0

Nikos C.
Nikos C.

Reputation: 51880

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.

Upvotes: 1

iheanyi
iheanyi

Reputation: 424

Try setting i * SIZE_OF_DATA + j to a variable, that may be where your problem lies.

Upvotes: 0

Math is Hard
Math is Hard

Reputation: 942

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.

Upvotes: 0

Related Questions