Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating C++ string in GDB

Tags:

c++

gdb

I'm having trouble creating an std::string (or any C++ object, I guess) in GDB. I tried lots of variations to the following and none of them seem to work:

(gdb) p std::string("hello") A syntax error in expression, near `"hello")'. 

Is there a way to do it?

(I'm surprised I couldn't find anything about this on the Web. I'm starting to think if my GDB is buggy or I'm doing something very wrong.)

like image 588
Johannes Sasongko Avatar asked Sep 15 '11 10:09

Johannes Sasongko


Video Answer


2 Answers

You should be able to construct a new std::string within the GDB. You want to allocate space on the heap to hold the std::string object, invoke the default constructor, and assign your string value. Here is an example:

(gdb) call malloc(sizeof(std::string)) $1 = (void *) 0x91a6a0 (gdb) call ((std::string*)0x91a6a0)->basic_string() (gdb) call ((std::string*)0x91a6a0)->assign("Hello, World") $2 = (std::basic_string<char, std::char_traits<char>, std::allocator<char> > &) @0x91a6a0: {static npos = <optimized out>, _M_dataplus = {<std::allocator<char>> = {<__gnu_cxx::new_allocator<char>> = {<No data fields>}, <No data fields>}, _M_p = 0x91a6f8 "Hello, World"}} (gdb) call SomeFunctionThatTakesAConstStringRef(*(const std::string*)0x91a6a0) 
like image 169
Jason Dillaman Avatar answered Oct 02 '22 17:10

Jason Dillaman


GDB cannot really do what you describe. Your case involves:

  1. instantiating a basic_string template and generating code for the class
  2. generate a call to constructor

This means it must do the work of the same complexity as a compiler. This is not the job of the debugger.

With that said, GDB is capable of evaluating a limited subset of statements, like calling an existing function with existing data and retrieving its result, since this won't involve generating a lot of code.

like image 39
Alex B Avatar answered Oct 02 '22 17:10

Alex B