Potential danger for using `convertToString().c_str()` in `Par_EquilibriumIC.cpp`
Opened this issue · 0 comments
koarakawaii commented
Problem Description
- Unable to get the correct content for the
char
array returned by the combining usage of the defined functionconvertToString()
along with theC++
c_str()
function. For the code snippet below, one will find the value forc
is empty, instead of the expected valueparams.ExtPot_Table_Name
.const char * c = convertToString(params.ExtPot_Table_Name).c_str(); fstream file; file.open(c, ios::in); # does not work
- Possible Explanation: If one use
convertToString(...).c_str()
without saving the intermediate productconvertToString(...)
, the object thus returned probably byconvertToString(...)
get freed immediately (probably because it is not referred any longer, see here), causing the value of the pointer returned byc_str()
becomes empty, since the original string object is freed and does not exist anymore (also see 3rd bullet point in Note).Notes
convertToString()
returns astring
objectc_str()
returns aconst char*
pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object (the object returned byconvertToString()
in this case)- The value of the pointer returned by
s.c_str()
will be changed if we simply overwrite the current value of the string objects
, even without touching the value of the pointer; see example code here
Workable Solutions
- use
strcpy
to copy the value (original solution)char c[MAX_STRING]; strcpy( c, convertToString(params.ExtPot_Table_Name).c_str() ); fstream file; file.open(c, ios::in);
- store the returned object by declaring a
string
objectstring s = convertToString(params.ExtPot_Table_Name); const char * c = s.c_str(); fstream file; file.open(c, ios::in);
- passing the C-String directly to a
const char *
pointer, even without using theconvertToString()
const char * c = params.ExtPot_Table_Name; fstream file; file.open(c, ios::in);