From b7f93c8cc0ba01789437ab892b946b753bbc0ff3 Mon Sep 17 00:00:00 2001
From: Florian Fischer <florian.fischer@muhq.space>
Date: Mon, 26 Jul 2021 11:13:52 +0200
Subject: [PATCH] [PipeSleepStrategy] use C++ smart ptrs instead of manual
 memory management

The destructor of PipeSleepStrategy caused segmentation faults when
running optimized. Because the stats pointer is not initialized it was
possibly to pass a garbage pointer to delete. Now we use a well defined
C++ smart pointer which fixes the problem and is more idiomatic anyway.
---
 emper/io/IoContext.cpp                     | 1 +
 emper/sleep_strategy/PipeSleepStrategy.hpp | 7 +++----
 2 files changed, 4 insertions(+), 4 deletions(-)

diff --git a/emper/io/IoContext.cpp b/emper/io/IoContext.cpp
index 83ab7001..550c55b4 100644
--- a/emper/io/IoContext.cpp
+++ b/emper/io/IoContext.cpp
@@ -12,6 +12,7 @@
 #include <cassert>	// for assert
 #include <cerrno>		// for errno, ECANCELED, EBUSY, EAGAIN, EINTR
 #include <cstring>	// for memset
+#include <memory>
 #include <ostream>	// for basic_osteram::operator<<, operator<<
 #include <string>
 #include <utility>
diff --git a/emper/sleep_strategy/PipeSleepStrategy.hpp b/emper/sleep_strategy/PipeSleepStrategy.hpp
index 5c60b747..5dc40304 100644
--- a/emper/sleep_strategy/PipeSleepStrategy.hpp
+++ b/emper/sleep_strategy/PipeSleepStrategy.hpp
@@ -9,6 +9,7 @@
 #include <cstddef>
 #include <cstdint>
 #include <iostream>
+#include <memory>
 #include <stdexcept>
 #include <type_traits>
 #include <vector>
@@ -131,7 +132,7 @@ class PipeSleepStrategy : AbstractWorkerSleepStrategy<PipeSleepStrategy>,
 		std::atomic<size_t> wakeupDueToNotify = 0;
 	};
 
-	Stats* stats;
+	std::unique_ptr<Stats> stats;
 
 	workerid_t workerCount;
 	int sleepFd;
@@ -253,12 +254,10 @@ class PipeSleepStrategy : AbstractWorkerSleepStrategy<PipeSleepStrategy>,
 		notifyFd = fds[1];
 
 		if constexpr (emper::STATS) {
-			stats = new Stats();
+			stats = std::make_unique<Stats>();
 		}
 	}
 
-	~PipeSleepStrategy() { delete stats; }
-
 	void printStats() { std::cout << *stats; }
 
 	[[nodiscard]] inline auto getSleeping() const -> long { return sleepers.load(); }
-- 
GitLab