Question

I have a problem which i cannot fix on my own.

string filenameRaw;
filenameRaw= argv[1];
function(filenameRaw.c_str(),...);

function(const char* rawDataFile,const char* targetfieldFile,const char* resultFile,const char* filename)
...
this->IOPaths.rawData=rawDataFile;
...

works very fine so far. Now I try to put another string in the variable IOPaths.rawData...

function(const char* rawDataFile,const char* targetfieldFile,const char* resultFile,const char* filename)
...
string filenameRaw;
filenameRaw=reader.Get("paths", "rawData", "UNKNOWN")
...
const char* rawDataFile1=filenameRaw.c_str();
cout << "Compare: " << strcmp(rawDataFile,rawDataFile1) <<endl;
...
this->IOPaths.rawData=rawDataFile1;

this does not work any more. Later in my programm I get errors with the filename. The strcmp definitly gives a 0, so the strings must be equal. Does anyone has an idea what i am doing wrong?

Was it helpful?

Solution

The validity of the output of c_str() is limited to, at most, the lifetime of the object on which c_str() was called.1

I suspect that this->IOPaths.rawData is pointing to deallocated memory once filenameRaw is out of scope.

An adequate remedy would be to pass the std::string around rather than [const] char*. A good stl implementation would use copy on write semantics for the string class so perhaps you wouldn't be repeatedly copying string data.


1In certain instances (such as if the object is modified), it could be less.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top