Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set breakpoint in C or C++ code programmatically for gdb on Linux

Tags:

c++

c

linux

gdb

People also ask

How do you set breakpoints in GDB C?

Setting breakpoints A breakpoint is like a stop sign in your code -- whenever gdb gets to a breakpoint it halts execution of your program and allows you to examine it. To set breakpoints, type "break [filename]:[linenumber]". For example, if you wanted to set a breakpoint at line 55 of main.

How do you add a breakpoint in Linux?

Breakpoints can be set for specific functions, lines or memory locations with the break command. To set a breakpoint on a specific function, use the command break function-name . For example, the following command sets a breakpoint at the start of the main function in the program above: $ gdb a.

What command is used in GDB to set a breakpoint?

Breakpoints are set with the break command (abbreviated b ). The debugger convenience variable `$bpnum' records the number of the breakpoint you've set most recently; see section Convenience variables, for a discussion of what you can do with convenience variables.

What is the GDB command to set a breakpoint in line 7?

c file listed in Example 7.1, “Compiling a C Program With Debugging Information” with debugging information, you can set a new breakpoint at line 7 by running the following command: (gdb) break 7 Breakpoint 2 at 0x4004e3: file fibonacci.


One way is to signal an interrupt:

#include <csignal>

// Generate an interrupt
std::raise(SIGINT);

In C:

#include <signal.h>
raise(SIGINT);

UPDATE: MSDN states that Windows doesn't really support SIGINT, so if portability is a concern, you're probably better off using SIGABRT.


By looking here, I found the following way:

void main(int argc, char** argv)
{
    asm("int $3");
    int a = 3;
    a++;  //  In gdb> print a;  expect result to be 3
}

This seems a touch hackish to me. And I think this only works on x86 architecture.


In a project I work on, we do this:

raise(SIGABRT);  /* To continue from here in GDB: "signal 0". */

(In our case we wanted to crash hard if this happened outside the debugger, generating a crash report if possible. That's one reason we used SIGABRT. Doing this portably across Windows, Mac, and Linux took several attempts. We ended up with a few #ifdefs, helpfully commented here: http://hg.mozilla.org/mozilla-central/file/98fa9c0cff7a/js/src/jsutil.cpp#l66 .)


Disappointing to see so many answers not using the dedicated signal for software breakpoints, SIGTRAP:

#include <signal.h>

raise(SIGTRAP); // At the location of the BP.

On MSVC/MinGW, you should use DebugBreak, or the __debugbreak intrinsic. A simple #ifdef can handle both cases (POSIX and Win32).