Should i free memory when i am using boost::posix_time::time_facet

I have a method that returns the expiration date of a subscription and uses boost::posix_time::time_facet to convert Unix time format to string. In tutorials I’ve seen, time_facet is created using the "new" keyword, but I haven’t seen any examples using "delete" (like in this thread). Should I free memory after using time_facet or does the stringstream automatically handle memory deallocation?
Here is my piece of code, does it has memory leak?

nlohmann::json GetExpireDate::ExecutePayload(ClientHandle& clientHandle)
{
    boost::posix_time::ptime pt = boost::posix_time::from_time_t(m_SubFromPacket.GetEndDate());
    std::stringstream ss;
    auto timeFacet = std::make_unique<boost::posix_time::time_facet>("%Y-%m-%d %H:%M:%S");
    ss.imbue(std::locale(std::locale::classic(), timeFacet.get()));
    ss << pt;
    return {{ "expire_date", ss.str()}};
}

>Solution :

Your code doesn’t contain a leak, but it does contain a double free. The locale takes ownership of its second argument. You must not delete it yourself (or let a unique_ptr do it).

Leave a Reply