Different output on ideone and devc++



For the problem CHEFBM I wrote this program … It seems to run fine on devc++ and gives the expected output 3 3 -1 4 but on ideone, it gives the output -1 -1 -1 -1

If I write a statement on line 52 cout<<""; which basically shouldn’t have any effect, the output changes to the expected 3 3 -1 4… link here

Can someone please point out what is happening?


One of the reasons such a problem can occur, is that adding the useless statements changes the way data and code are stored in the different segments (text, stack, heap etc.) of the program.

When you access information that you haven’t initialized or a variable index is out of bounds, you may get unexpected behavior because of the reason above.

I found two mistakes in the program:

Line 61: while((a[curr].first==i)&&curr!=p)

Let’s address this one first. The way short-circuiting (google it) works, a[curr] gets accessed before curr != p is checked. Indices of a must be between 0 and p - 1, making this an instance of variable index out of bounds situation. Since curr!=p does get checked, it should not cause unexpected behavior (it might throw a RTE though, so reorder the conditions anyway.)

Line 75: if(z[j-1]-z[j]>1)

z[m] here, gets accessed because of the for loop right above this line. Out of bounds again. This is probably why your program does’t work.

Fix that and your program should run just fine.