c++debugginggdb

GDB error when reading an std::string variable


#include <string>

struct S
{ 
  S(const std::string& es)
    : first_string(func().c_str())
  {}

  std::string func()
  {
    std::string my_string = "some string"; // Breakpoint here
    return my_string;
  }

  std::string first_string;
  std::string second_string;
};

int main()
{
  std::string foo;
  S s("mystring");
}

If I place a breakpoint right at the initialization of my_string, and try to either print the value of my_string or info locals, then I'm getting the following error:

my_string = <error reading variable: Cannot create a lazy string with address 0x0, and a non-zero length.>

Tested with gdb 8.2-20. Is this a gdb issue or something expected? Any changes to the given code (for example, removing any of the other variables) gets rid of the issue.


Solution

  • A breakpoint stops execution before the line its placed on. So you are trying to read an uninitialized string, and the error is expected. If you were to step forward in execution (or place the breakpoint one line later) I suspect you wouldn't encounter this error.