The problem is caused by returning a pointer to a local variable. When the function GetParamFromLine
returns the variable text
goes out of scope. The pointer returned is no longer valid, resulting in undefined behavior. You have to return the data in some other way, for example:
std::string txtval=GetParamFromLine("WINDOW_WIDTH");
val = atol(txtval.c_str());
std::string GetParamFromLine(char*parameter)
{
char text[16];
//
// do the reading procedure and fill the text
//
return std::string(text);
}
Changing the return type from a pointer to a local to std::string
alleviates the problem of returning a pointer to a local variable. The resources used by std::string
are managed by the object and are cleaned up automatically.
As an alternative you could remove the atol
call as well and use a std::istringstream
instead. One benefit is that this allows for better error reporting:
std::string txtval=GetParamFromLine("WINDOW_WIDTH");
std::istringstream iss(txtval);
int val( 0 );
iss >> val;
Now if you really want to go over the top you could combine both retrieval of the string and conversion to an integral data type, and parameterize the return type of this new function template:
template<typename T>
T GetValueFromLine(const std::string& param) {
std::string txtval=GetParamFromLine(param.c_str);
std::istringstream iss(txtval);
T val = T();
iss >> val;
return val;
}
With this template you can do the following:
long wndWidth = GetValueFromLine<long>("WINDOW_WIDTH");
bool showInfo = GetValueFromLine<bool>("SHOW_INFO");
....
Note: Error handling omitted.