Skip to content

Commit

Permalink
Merge pull request #239 from scratchcpp/fix_value_memory_leaks
Browse files Browse the repository at this point in the history
Fix #235: Fix memory leaks in Value assignment operators
  • Loading branch information
adazem009 authored Oct 1, 2023
2 parents f222177 + e7dbd28 commit dcc6e08
Showing 1 changed file with 49 additions and 8 deletions.
57 changes: 49 additions & 8 deletions include/scratchcpp/value.h
Original file line number Diff line number Diff line change
Expand Up @@ -372,76 +372,117 @@ class LIBSCRATCHCPP_EXPORT Value

const Value &operator=(float v)
{
if (m_type == Type::String)
m_stringValue.~basic_string();

m_type = Type::Double;
m_doubleValue = v;
return *this;
}

const Value &operator=(double v)
{
if (m_type == Type::String)
m_stringValue.~basic_string();

m_type = Type::Double;
m_doubleValue = v;
return *this;
}

const Value &operator=(int v)
{
if (m_type == Type::String)
m_stringValue.~basic_string();

m_type = Type::Integer;
m_intValue = v;
return *this;
}

const Value &operator=(long v)
{
if (m_type == Type::String)
m_stringValue.~basic_string();

m_type = Type::Integer;
m_intValue = v;
return *this;
}

const Value &operator=(bool v)
{
if (m_type == Type::String)
m_stringValue.~basic_string();

m_type = Type::Bool;
m_boolValue = v;
return *this;
}

const Value &operator=(const std::string &v)
{
m_type = Type::String;
new (&m_stringValue) std::string(v);
if (m_type == Type::String)
m_stringValue = v;
else {
new (&m_stringValue) std::string(v);
m_type = Type::String;
}

initString(v);
return *this;
}

const Value &operator=(const char *v)
{
m_type = Type::String;
new (&m_stringValue) std::string(v);
if (m_type == Type::String)
m_stringValue = v;
else {
new (&m_stringValue) std::string(v);
m_type = Type::String;
}

initString(v);
return *this;
}

const Value &operator=(const Value &v)
{
m_type = v.m_type;

switch (m_type) {
switch (v.m_type) {
case Type::Integer:
if (m_type == Type::String)
m_stringValue.~basic_string();

m_intValue = v.m_intValue;
break;

case Type::Double:
if (m_type == Type::String)
m_stringValue.~basic_string();

m_doubleValue = v.m_doubleValue;
break;

case Type::Bool:
if (m_type == Type::String)
m_stringValue.~basic_string();

m_boolValue = v.m_boolValue;
break;

case Type::String:
new (&m_stringValue) std::string(v.m_stringValue);
if (m_type == Type::String)
m_stringValue = v.m_stringValue;
else
new (&m_stringValue) std::string(v.m_stringValue);
break;

default:
break;
}

m_type = v.m_type;

return *this;
}

Expand Down

0 comments on commit dcc6e08

Please sign in to comment.