Search code examples
cdebuggingx86gdbbreakpoints

GDB not setting breakpoint on desired line


In GDB, I am trying to set breakpoint on line 4 but it always puts a breakpoint at line 5. Even if I put break main, it puts point on line 5, whereas line 4 is the first line. Why and how can I fix this?

In my coding directory, i have main.c file with the following contents:

#include <stdio.h>

int main() {
    int i;   // line 4
    for (i = 0; i < 10; i++) {
        printf("Hello world!\n");
    }
    return 0;
}

Now I compiled it with gcc for x86 architecture and with extra debugging info... gcc -m32 -g main.c And I am using gdb to examine the a.out: gdb -q ./a.out And when i put break main it sets breakpoint at line 5, the for (i = 0; i < 10; i++) { line. Even if I explicitly put breakpoint on line 4 with break 4, it still sets breakpoint at line 5 with the code for (i = 0; i < 10; i++) {. Here is an example:

$ gdb -q a.out
Reading symbols from a.out...
(gdb) break 4
Breakpoint 1 at 0x11aa: file main.c, line 5.
(gdb)

Why is this not setting a breakpoint at the line 4? What can be the cause? And How do I fix it?


Solution

  • You can't set a breakpoint on line 4 because it's a declaration with no initializer, not a statement, so there is no assembly instruction associated with it.

    If you initialize i, then there will be an assembly instruction that goes with it, so you should be able to set a breakpoint after that.