[Ovmsdev] OvmsMetricString memory lifecycle

Tom Parker tom at carrott.org
Tue Aug 21 04:06:06 HKT 2018


On 21/08/18 05:19, Michael Balzer wrote:
> in no case can passing & returning string objects by value result in a use after free or memory leak. Pass by value guarantees you'll be operating on a copy as
> soon as necessary, and all compiler generated copies are guaranteed to be freed by the compiler.

Ah, pass by value isn't something I had considered.

However what happens in:

void OvmsMetricString::SetValue(std::string value)
   {
   if (m_value.compare(value)!=0)
     {
     m_value = value;
     SetModified(true);
     }
   else
     SetModified(false);
   }


value is passed in and then assigned to the member variable. If value is 
freed when SetValue() returns, is another copy made during the 
assignment? Will this potentially fragment the memory? Would 
m_value.assign(value); be better (assuming the backing store buffer 
isn't resized too often), or does m_value = value end up doing the same 
thing?


I found my bug with the simcom status command -- I messed up the 
parameter somewhere between when I tested it and finished up for the 
day. First, it's not even the right parameter, and second, I'm printf 
%s'ing the object not the c_str().



More information about the OvmsDev mailing list