9

I've got test program like below:

#include<memory>
#include<iostream>
using namespace std;

int main()
{
    shared_ptr<int> si(new int(5));
    return 0;
}

Debug it:

(gdb) l
1   #include<memory>
2   #include<iostream>
3   using namespace std;
4   
5   int main()
6   {
7       shared_ptr<int> si(new int(5));
8       return 0;
9   }
10  
(gdb) b 8
Breakpoint 1 at 0x400bba: file testshare.cpp, line 8.
(gdb) r
Starting program: /home/x/cpp/x01/a.out 

Breakpoint 1, main () at testshare.cpp:8
8       return 0;
(gdb) p si
$1 = std::shared_ptr (count 1, weak 0) 0x614c20

It only prints out the pointer type information of si, but how to get the value stored in it (in this case 5)? How can I check the internal content of si during debugging?

Rakete1111
  • 47,013
  • 16
  • 123
  • 162
Troskyvs
  • 7,537
  • 7
  • 47
  • 115
  • What do you mean with *"the value store in si"*? The value of the `int` `si` points to? – Baum mit Augen Jan 02 '17 at 02:48
  • Possible duplicate of [How to access target of std::tr1::shared\_ptr in GDB](https://stackoverflow.com/questions/24917556/how-to-access-target-of-stdtr1shared-ptr-in-gdb) | `unique_ptr`: https://stackoverflow.com/questions/22798601/how-to-debug-c11-code-with-unique-ptr-in-ddd-or-gdb – Ciro Santilli OurBigBook.com Sep 24 '17 at 12:01

2 Answers2

6

Try the following:

p *si._M_ptr

Now, this assumes that you're using libstdc++.so, given the output for p si.

Alternatively, you could use the value 0x614c20 directly (from your output):

p {int}0x614c20

Both should display the value 5.

geipel
  • 395
  • 1
  • 3
  • 9
3

but how to get the value stored in it

You will have to cast raw pointer to actual pointer type stored in std::shared_ptr. Use whatis to know what the actual pointer type is.

(gdb) p si
$8 = std::shared_ptr (count 1, weak 0) 0x614c20
(gdb) whatis si
type = std::shared_ptr<int>
(gdb) p *(int*)0x614c20
$9 = 5
ks1322
  • 33,961
  • 14
  • 109
  • 164