I'm trying to debug a program that has no source code available, and I need to look at what it has stored in a std::string. I've been Googling and looking on here, and I've found some information about outputting STL containers, but all of it refers to variables, with no source or debug information all I have is a memory offset of the class data. Is there any way to do this?
Asked
Active
Viewed 2.6k times
2 Answers
38
Every std::string
implementation has a pointer to the raw characters in it somewhere. For g++ 4.x
, that pointer is at offset 0
into the string.
If you know that the string resides at e.g. 0x7fffffffda88
, then
print *(char**)0x7fffffffda88
is what you need.

Employed Russian
- 199,314
- 34
- 295
- 362
-
1Thank you, that worked. One thing I'd like to know is how I'd figure something like that out myself. i.e. given the source code for class 'X' how would I figure out the position of fields within that class? The only way I can think of at the moment is to compile my own test application and examine the pointers I'm given (with offsetof, etc). – PeterBelm Jul 21 '11 at 15:55
-
2The fastest way to figure out the offset is in fact to compile a trivial test program using the given class in debug mode, and examine the offsets and class layout in GDB. That's exactly what I've done to answer your question ;-) – Employed Russian Jul 22 '11 at 05:23
-
2As an aside, if SSO is used like in clang's libc++, there is no such pointer for small strings. ;-) – Deduplicator Oct 13 '15 at 16:39
-
This is so helpful. I am trying to look into a std::string variable when debugging a core dump. However, command like "p s.size()" or "p s.c_str()" do not work in this case (gdb will annoyingly keep saying "You can't do that without a process to debug" ). The method posted here gives a workaround. – linbianxiaocao Nov 25 '15 at 21:01
30
Perhaps the easiest option is to use the c_str
method, as in:
print myStr.c_str()

Nadav
- 1,023
- 9
- 10