The problem is that you are casting the cTime_ variable without first allocating memory. I'm not sure if this is a global variable or a member variable, but first you need to use the โnewโ operator to highlight it. This way, you return a pointer to the (address) of this variable back to the calling function, but as soon as this function completes, it deletes the "temp" variable, and therefore the pointer you return will point to invalid memory.
The solution would be to use the โnewโ operator:
string* Recipe::getCookingTime() // @intput: none // @output: cooking time as a string { string displayHrs; string displayMins; if( cookingTime_->numHours < 10 ) displayHrs = intToString(0) + intToString(cookingTime_->numHours ); else displayHrs = intToString(cookingTime_->numHours ); if( cookingTime_->numMinutes < 10 ) displayMins = intToString(0) + intToString(cookingTime_->numMinutes); else displayMins = intToString(cookingTime_->numMinutes); if( NULL == cTime_ ) { cTime_ = new string(); } *cTime_ = "The time to cook the recipe is " + displayHrs + ":" + displayMins; return cTime_; }
However, I must warn you that this is not a very good design, because here you allocate memory and require the call to know that it should free it when it ends with it. The preferred way to do this should be for the caller to allocate the variable and then pass the pointer:
bool Recipe::getCookingTime( string* str ) // @intput: none // @output: cooking time as a string { if( NULL == str ) { // Received invalid pointer return false; } string displayHrs; string displayMins; if( cookingTime_->numHours < 10 ) displayHrs = intToString(0) + intToString(cookingTime_->numHours ); else displayHrs = intToString(cookingTime_->numHours ); if( cookingTime_->numMinutes < 10 ) displayMins = intToString(0) + intToString(cookingTime_->numMinutes); else displayMins = intToString(cookingTime_->numMinutes); *str = "The time to cook the recipe is " + displayHrs + ":" + displayMins; return true; }
Then, when the caller wants to use the function, he can do this:
cTime_ = new string(); getCookingTime( cTime_ );
Summary It is important to remember that you must allocate the memory that the pointer points to before attempting to assign it. In addition, the generally poor design allows you to allocate memory (using the new operator) inside the function and not explicitly delete it. The one who allocates memory should always always free it
source share