Skip to content

Commit e46bf12

Browse files
authored
Fix memory leak in PointerVector pushBack (#1487)
1 parent ac99bbd commit e46bf12

File tree

3 files changed

+22
-4
lines changed

3 files changed

+22
-4
lines changed

Common++/header/PointerVector.h

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
#pragma once
22

3+
#include <cstddef>
34
#include <stdio.h>
45
#include <stdint.h>
56
#include <stdexcept>
@@ -121,19 +122,36 @@ namespace pcpp
121122
m_Vector.clear();
122123
}
123124

125+
/**
126+
* Adding a nullptr to the vector is not allowed.
127+
*/
128+
void pushBack(std::nullptr_t element, bool freeElementOnError = true) = delete;
129+
124130
/**
125131
* Add a new (pointer to an) element to the vector
126132
* @param[in] element A pointer to an element to assume ownership of.
133+
* @param[in] freeElementOnError If set to true, the element is freed if an exception is thrown during the push.
127134
* @throws std::invalid_argument The provided pointer is a nullptr.
128135
*/
129-
void pushBack(T* element)
136+
void pushBack(T* element, bool freeElementOnError = true)
130137
{
131138
if (element == nullptr)
132139
{
133140
throw std::invalid_argument("Element is nullptr");
134141
}
135142

136-
m_Vector.push_back(element);
143+
try
144+
{
145+
m_Vector.push_back(element);
146+
}
147+
catch (const std::exception&)
148+
{
149+
if (freeElementOnError)
150+
{
151+
delete element;
152+
}
153+
throw;
154+
}
137155
}
138156

139157
/**

Packet++/header/Asn1Codec.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -321,7 +321,7 @@ namespace pcpp
321321
{
322322
auto encodedRecord = (*recordIter)->encode();
323323
auto copyRecord = Asn1Record::decode(encodedRecord.data(), encodedRecord.size(), false);
324-
m_SubRecords.pushBack(copyRecord.release());
324+
m_SubRecords.pushBack(std::move(copyRecord));
325325
recordValueLength += encodedRecord.size();
326326
}
327327

Packet++/src/LdapLayer.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -749,7 +749,7 @@ namespace pcpp {
749749
Asn1OctetStringRecord typeRecord(attribute.type);
750750
Asn1SetRecord valuesRecord(valuesSubRecords);
751751

752-
attributesSubRecords.pushBack(new Asn1SequenceRecord({&typeRecord, &valuesRecord}));
752+
attributesSubRecords.pushBack(new Asn1SequenceRecord({ &typeRecord, &valuesRecord }));
753753
}
754754

755755
Asn1OctetStringRecord objectNameRecord(objectName);

0 commit comments

Comments
 (0)