user2836797
user2836797

Reputation:

Why and when does this char * change values?

Observe the following code. The reason I am juggling from std::string to c-style string and back to std::string is because bmd2create is part of a C Binding API and it must take a c-style string. Otherwise I am using std::string whenever possible.

OtherFile.h

void bmd2create(const char * filename) {
  std::string sFileName (filename);

  // do things with sFileName

  std::ostringstream ostr;
  ostr << "\t(in)  filename       = " << filename << "\n";
  logger.log(Logger::LogLevel::LOG_DEBUG, ostr.str());
}

Main.cpp

const char * filename = std::string(filepath + "dataset1.out").c_str();

// *filename is 46 '.'

bmd2create(filename);

// *filename is now 0 '\0'

The question

Where and why is the filename pointer being moved? And what is the best way to move it back to the start of the string?

Upvotes: 2

Views: 82

Answers (1)

Ben Voigt
Ben Voigt

Reputation: 283624

This line is particularly useless:

const char * filename = std::string(filepath + "dataset1.out").c_str();

You create a temporary std::string, and then get a pointer to its content with c_str(). The temporary variable gets cleaned up at the end of the full-expression, before the next line executes. At that point the pointer is going nowhere. Using it is undefined behavior.

The reason you think the pointer is ok before the call to bmd2create is that the memory pointed to hasn't been overwritten yet. But it is no longer owned by the string, so any future allocation can replace it with a new object.

Correct code would be:

std::string filename = std::string(filepath) + "dataset1.out";
bmd2create(filename.c_str());

Upvotes: 7

Related Questions