7

I am using gdb-7.0.1 and I think I have detected a bug in a certain section of my code, which has a for loop. The for loop looks like

for (int i=0 ; i< end ; ++i )
{
   //Code here.
}

Here end is a very large integer. The code does not crash at the first iteration, and seems to crash somewhere at iteration number end/2.

Since I want to understand the behaviour of the code at iteration number end/2 , just stepping and nexting from i=0 till I reach this iteration point, is unfeasible.

Is there a way to tell gdb to continue through a for loop till i gets the value end/2 and then wait for the user to manually step through iteration number end/2?

I am using gcc-4.5.2 on Ubuntu Linux

smilingbuddha
  • 14,334
  • 33
  • 112
  • 189

5 Answers5

6

Here's a tutorial on conditional breakpoints with gdb.

I'm guessing you didn't know the term for this, otherwise it would have been easy to google.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
5

When you set the breakpoint it'll give you a breakpoint number (for the moment, let's assume it's 1). You'll then make that breakpoint conditional, something like:

condition 1 i==end/2
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
5

You have to use conditional breakpoint. Here is more about it: http://www.cs.cmu.edu/~gilpin/tutorial/#3.4

And on SO: How do I set a conditional breakpoint in gdb, when char* x points to a string whose value equals "hello"?

In your case (not tested):

break <line_number> if i==end/2
Community
  • 1
  • 1
psur
  • 4,400
  • 26
  • 36
1

You should be able to place an if (i == (end/2 -1)) { Foo; } in there then set a breakpoint at Foo, which would allow you to continue stepping from there.

Michael Wilson
  • 442
  • 1
  • 4
  • 11
  • +1 as this used to be my method until I found conditional breakpoints as @LuchianGrigore suggests. – Ash Burlaczenko Apr 16 '12 at 18:25
  • Thanks yeah, I'm not sufficiently fluent in gdb to have picked up on it. I figured it was a sufficiently generic solution to leave it up even in the face of the more poignant ones. – Michael Wilson Apr 16 '12 at 18:28
1

If end is big (in the tens of thousands), then the conditional breakpoint solution can be very slow - gdb has to evaluate the condition each time round the loop. If this is a problem for you, then you can use this trick:

for (int i=0 ; i< end ; ++i )
{
   if (i == end/2)
      i %= end ; // This has no effect, but lets you set a breakpoint here
   //Code here.
}

I do this all the time :-)

Another solution is to set a skip-count on the breakpoint. I use gdb in a Qt environment, so I can't give you the gdb syntax. But it's faster than setting a condition.

TonyK
  • 16,761
  • 4
  • 37
  • 72