Skip to content

Commit

Permalink
Fix memory leak in PointerVector pushBack (#1487)
Browse files Browse the repository at this point in the history
  • Loading branch information
Dimi1010 authored Jul 29, 2024
1 parent ac99bbd commit e46bf12
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 4 deletions.
22 changes: 20 additions & 2 deletions Common++/header/PointerVector.h
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#pragma once

#include <cstddef>
#include <stdio.h>
#include <stdint.h>
#include <stdexcept>
Expand Down Expand Up @@ -121,19 +122,36 @@ namespace pcpp
m_Vector.clear();
}

/**
* Adding a nullptr to the vector is not allowed.
*/
void pushBack(std::nullptr_t element, bool freeElementOnError = true) = delete;

/**
* Add a new (pointer to an) element to the vector
* @param[in] element A pointer to an element to assume ownership of.
* @param[in] freeElementOnError If set to true, the element is freed if an exception is thrown during the push.
* @throws std::invalid_argument The provided pointer is a nullptr.
*/
void pushBack(T* element)
void pushBack(T* element, bool freeElementOnError = true)
{
if (element == nullptr)
{
throw std::invalid_argument("Element is nullptr");
}

m_Vector.push_back(element);
try
{
m_Vector.push_back(element);
}
catch (const std::exception&)
{
if (freeElementOnError)
{
delete element;
}
throw;
}
}

/**
Expand Down
2 changes: 1 addition & 1 deletion Packet++/header/Asn1Codec.h
Original file line number Diff line number Diff line change
Expand Up @@ -321,7 +321,7 @@ namespace pcpp
{
auto encodedRecord = (*recordIter)->encode();
auto copyRecord = Asn1Record::decode(encodedRecord.data(), encodedRecord.size(), false);
m_SubRecords.pushBack(copyRecord.release());
m_SubRecords.pushBack(std::move(copyRecord));
recordValueLength += encodedRecord.size();
}

Expand Down
2 changes: 1 addition & 1 deletion Packet++/src/LdapLayer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -749,7 +749,7 @@ namespace pcpp {
Asn1OctetStringRecord typeRecord(attribute.type);
Asn1SetRecord valuesRecord(valuesSubRecords);

attributesSubRecords.pushBack(new Asn1SequenceRecord({&typeRecord, &valuesRecord}));
attributesSubRecords.pushBack(new Asn1SequenceRecord({ &typeRecord, &valuesRecord }));
}

Asn1OctetStringRecord objectNameRecord(objectName);
Expand Down

0 comments on commit e46bf12

Please sign in to comment.