weird bug

I have a small section of code that wasn't working properly, so I used "cout" to display some of the variables, to see what was going on, and it started working only by adding the cout line. That shouldn't affect anything, so I'm hoping someone has an idea on why this is happening.

Here is the code without the "cout", which doesn't work
1
2
3
4
5
6
7
8
9
10
11
12
//cx and cy are defined before this as ints
//leftFound is defined as bool
while(cx>=0&&!leftFound){
   unsigned char darkness;
   darkness=getDarkness(buffer,cx,cy);
   if(darkness<30){
      leftFound=true;
      leftx=cx;
      lefty=cy;
   }
   cx--;
}


By just changing the code to this, it works perfectly
1
2
3
4
5
6
7
8
9
10
11
12
13
//cx and cy are defined before this as ints
//leftFound is defined as bool
while(cx>=0&&!leftFound){
   unsigned char darkness;
   darkness=getDarkness(buffer,cx,cy);
   cout<<"";//this line was added, which does nothing
   if(darkness<30){
      leftFound=true;
      leftx=cx;
      lefty=cy;
   }
   cx--;
}


This program is not multi-threaded, so that shouldn't be messing with it. I just have no idea why that one line would change anything.

The section of code is just starting at a certain point (cx,cy) and moving to the left until it finds a pixel of a certain darkness
Last edited on
smells like memory corruption.

Check to make sure you're not stepping out of bounds on any of your arrays. And make sure you aren't dereferencing any bad pointers.
getDarkness() sounds like the most likely problem. Look at "buffer" specifically in respect to what Disch said.
I figured it out.
It was a problem with my getDarkness() method. After stepping through it with a debugger, I found that I had a local variable that I didn't initialize to zero, so it was returning garbage. Although I still don't understand how the "cout" line fixed this.

here is the getDarkness() method if you want to see it (it just returns the average of the RGB of the pixel)
1
2
3
4
5
6
7
unsigned int getDarkness(IplImage* img,int x,int y){
   unsigned int total;
   total+=getR(img,x,y);
   total+=getG(img,x,y);
   total+=getB(img,x,y);
   return total/3;
}
Last edited on
The cout line most likely called a function using parameters that happened to put a zero in the place where total was allocated. You should compile you stuff with -Wall -Wextra, it catches these simple errors.
Topic archived. No new replies allowed.