Mantis Issue 513, reported by lhermitte, assigned to jmichel, created: 2012-02-07
In several places a pointer to the inner chars buffer of a temporary string variable is extracted. When the string is released (on the ';' sequence point) the pointer points to nothing valid and applications may crash.
Where COW implementations of std::string are used (GNU's libstdc++, STLport), the code may fall into order. Indeed when the string returned is a copy (why BTW ? This is not efficient) of a string stored elsewhere (like in a std::map, see for instance ApplicationOptionResult::GetParameterString), the actual buffer of chars is (ref-count-)shared and the application still runs.
This is a side effect. Next gen implementations of std::string won't permit that as COW implementations have been (voluntarily) deprecated from 2011 C++ standard. VC++/dinkumware implementation is likely to become the new de-facto behavioural standard.
Hence, OTB will crash more and more often on unixes platforms.
NB: the bug was initially detected on a windows platform, in the old OTB-Applications/Classification/otbLabeledImageColorMapping.cxx
Suggestion: hunt down all appearances of c_str() to check they are not applied on temporary variables. typically a
find . -type f |xargs grep ").c_str"
shall do the trick (I count 971 occurrences in the latest branch).
N.B.: The only valid uses are when the returned pointer is immediately consumed (and not stored) in a function e.g.
const int i = atoi(GetFoo("bar").c_str()); // BTW atoi is a code smell because of its defensive approach (to ignore failures)