12

How can I access target of a std::tr1::shared_ptr in GDB. This doesn't work:

(gdb) p sharedPtr->variableOfTarget

If I try with the pointer object itself (p sharedPtr) I get something like this:

$1 = std::tr1::shared_ptr (count 2) 0x13c2060

With a normal pointer I can do p *ptr and get all the data or p ptr->variable for just one variable.

I'm on Centos 6.5, GCC 4.4.7-4.el6 and GDB 7.2-64.el6_5.2.

Pnog is not Pong
  • 175
  • 1
  • 1
  • 8

3 Answers3

34

ptr->get() not always work.

when i try ptr->get(), gdb complains for: can not resolve method ***:get() to any overloaded instance

I eventually go to /usr/include/ to find the source code of shared_ptr to see the private member.

It turns out to be

ptr._M_ptr

It works for me. Source code works for everyone.

boydc2011
  • 567
  • 1
  • 5
  • 7
  • You meant ptr.get() right? I think the operator `->` is not what you want use here. – Raydel Miranda Feb 09 '15 at 23:38
  • ptr->get() means *ptr.get(). – boydc2011 Feb 27 '15 at 03:27
  • 3
    Nop, is not the same, `ptr->get()` is an attemp to call the `get` function from whatever the shared_ptr is pointing to, and `*ptr.get()` is dereferencing that pointer. The `.` operator has preference here. `*ptr.get()` is the same that `*(ptr.get())`. – Raydel Miranda Feb 27 '15 at 12:59
12

Try with

(gdb) p (*sharedPtr.get())

that function returns the a pointer to the object owned by the smart pointer.

Raydel Miranda
  • 13,825
  • 3
  • 38
  • 60
  • You have to use asterisk in front to get access to the pointer target and for some reason also parentheses like this: `(*sharedPtr.get())`. See my comment to the question. – Pnog is not Pong Jul 23 '14 at 19:12
  • If I use this solution I get `(gdb) p (*self.get()) You can't do that without a process to debug.` – Rostfrei Dec 18 '18 at 14:56
8

Answer first:

p *frame._M_ptr # frame is the shared_ptr's name

I tried p (*frame.get()), but it didn't work(frame is my shared_ptr name)

(gdb) p frame
$4 = std::shared_ptr (count 2, weak 0) 0x2ea3080
(gdb) p (*frame.get())
Cannot evaluate function -- may be inlined

then I tried to get what's in this shared_ptr, then I found this

(gdb) p frame.
_M_get_deleter  __shared_ptr    operator*       reset           unique          ~shared_ptr     
_M_ptr          get             operator->      shared_ptr      use_count       
_M_refcount     operator bool   operator=       swap            ~__shared_ptr   

I used it's _M_ptr field, it worked.

(gdb) p *frame._M_ptr 
$5 = {
...
}

I used std::shared_ptr, and gdb 7.6.

vacing
  • 646
  • 6
  • 9