Skip to content

Commit b9b82a1

Browse files
committed
Fix potential memory leak in Family
1 parent 7607cbe commit b9b82a1

File tree

3 files changed

+25
-5
lines changed

3 files changed

+25
-5
lines changed
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
#pragma once
2+
3+
#include <memory>
4+
#include <utility>
5+
6+
namespace prometheus {
7+
namespace detail {
8+
9+
// Remove as soon C++14 can be used.
10+
template <typename T, typename... Args>
11+
std::unique_ptr<T> make_unique(Args&&... args) {
12+
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
13+
}
14+
15+
} // namespace detail
16+
} // namespace prometheus

core/include/prometheus/family.h

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
#include "prometheus/check_names.h"
1616
#include "prometheus/client_metric.h"
1717
#include "prometheus/collectable.h"
18+
#include "prometheus/detail/future_std.h"
1819
#include "prometheus/metric_family.h"
1920

2021
namespace prometheus {
@@ -162,11 +163,12 @@ T& Family<T>::Add(const std::map<std::string, std::string>& labels,
162163
#endif
163164
return *metrics_iter->second;
164165
} else {
165-
auto metric = new T(std::forward<Args>(args)...);
166-
metrics_.insert(std::make_pair(hash, std::unique_ptr<T>{metric}));
166+
auto metric =
167+
metrics_.insert(std::make_pair(hash, detail::make_unique<T>(args...)));
168+
assert(metric.second);
167169
labels_.insert({hash, labels});
168-
labels_reverse_lookup_.insert({metric, hash});
169-
return *metric;
170+
labels_reverse_lookup_.insert({metric.first->second.get(), hash});
171+
return *(metric.first->second);
170172
}
171173
}
172174

core/tests/family_test.cc

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
#include <gmock/gmock.h>
66

77
#include "prometheus/client_metric.h"
8+
#include "prometheus/detail/future_std.h"
89
#include "prometheus/histogram.h"
910

1011
namespace prometheus {
@@ -65,7 +66,8 @@ TEST(FamilyTest, add_twice) {
6566

6667
TEST(FamilyTest, should_assert_on_invalid_metric_name) {
6768
auto create_family_with_invalid_name = []() {
68-
return new Family<Counter>("", "empty name", {});
69+
return detail::make_unique<Family<Counter>>(
70+
"", "empty name", std::map<std::string, std::string>{});
6971
};
7072
EXPECT_DEBUG_DEATH(create_family_with_invalid_name(),
7173
".*Assertion `CheckMetricName.*");

0 commit comments

Comments
 (0)