ABu
ABu

Reputation: 12299

GDB: breakpoint when calling destructor of specific object

In my app, I'm getting a SIGSEGV fault after trying to access a field inside a widget pointer. That widget comes from a 3rd-party library. I know exactly the point where the signal is being thrown. What I want to know, is if in that specific moment, the "this" pointer of the faulty widget has been deleted or not, and when that happened.

So, the idea is to set a breakpoint at a place where I know my object does exist, and, and here is where my question borns, say to gdb: "break when the destructor of this specific "this" pointer is called". How can I tell gdb to do that?

In such a case, a can know if the object is deleted before the signal is thrown, and where and why that object has been deleted (to fix the situation).

Upvotes: 4

Views: 3921

Answers (1)

Employed Russian
Employed Russian

Reputation: 213809

How can I tell gdb to do that?

Use conditional breakpoint. Example:

cat -n t.cc
     1  struct Foo {
     2    ~Foo() {}
     3  };
     4  
     5  Foo *af1, *af2;
     6  int main()
     7  {
     8    Foo f1;
     9    af1 = &f1;
    10    {
    11      Foo f2;
    12      af2 = &f2;
    13    }
    14  }

g++ -g t.cc && gdb -q ./a.out

(gdb) b 12
Breakpoint 1 at 0x400500: file t.cc, line 12.
(gdb) r
Starting program: /tmp/a.out 

Breakpoint 1, main () at t.cc:12
12      af2 = &f2;
(gdb) p &f2
$1 = (Foo *) 0x7fffffffdc9f
(gdb) p &f1
$2 = (Foo *) 0x7fffffffdc9e
(gdb) b 'Foo::~Foo()' if this == 0x7fffffffdc9f
Breakpoint 2 at 0x400532: file t.cc, line 2.
(gdb) c
Continuing.

Breakpoint 2, Foo::~Foo (this=0x7fffffffdc9f, __in_chrg=<optimized out>) at t.cc:2
2     ~Foo() {}
(gdb) bt
#0  Foo::~Foo (this=0x7fffffffdc9f, __in_chrg=<optimized out>) at t.cc:2
#1  0x0000000000400517 in main () at t.cc:12
(gdb) c
Continuing.
[Inferior 1 (process 121877) exited normally]

Voila: breakpoint was hit when f2 was destructed, but not when f1 was.

Upvotes: 6

Related Questions