0

I try to convert uint64_t to const char *. But I find If I use
const char *sz2 = std::to_string(channel_id2).c_str();, it print nothing.

when I use string to take std::to_string(channel_id2)'s result and convert the string to const char *, it can print the infomation normally. Then I make other experiments.

enter image description here

enter image description here

enter image description here

cat
  • 11
  • 1

1 Answers1

0

This is fine:

// This creates a temp string
std::string temp = std::to_string(channel_id2);

// This is fine, because temp is a variable (and so exists in memory)
const char *sz2 = temp.c_str();

However, when you do:

const char *sz2 = std::to_string(channel_id2).c_str();

The order of operations is:

  1. Call std::to_string, which generates a temporary string object.
  2. Use c_str() to get a pointer to the temporary string contents
  3. Free the temporary string (thus freeing the memory that sz2 is pointing too)

The result is that sz2 is pointing at nothing valid, and so you get nonsense results printed out

Or to translate your one line of code across multiple lines, this is what is happening:

const char *sz2; //< uninitialised

// scope the lifespan of the temporary
{
  // generate temp
  std::string temp = std::to_string(channel_id2);

  // grab address..
  sz2 = temp.c_str();

  // at this point, the destructor of temp is called... 
}

// now sz2 is invalid from here
robthebloke
  • 9,331
  • 9
  • 12