[statsd] Fix a memory leak
Reported by the static analyzer:
frameworks/base/cmds/statsd/src/main.cpp:81:16: warning: Potential leak
of memory pointed to by 'data' [clang-analyzer-cplusplus.NewDeleteLeaks]
Bug: None
Test: Built with the static analyzer; warning disappeared.
Change-Id: Icf2cfb4bc4b397d8664e91ddb6c6e346c33ec4ac
diff --git a/cmds/statsd/src/main.cpp b/cmds/statsd/src/main.cpp
index e8904c6..6aa68da 100644
--- a/cmds/statsd/src/main.cpp
+++ b/cmds/statsd/src/main.cpp
@@ -29,6 +29,8 @@
#include <utils/Looper.h>
#include <utils/StrongPointer.h>
+#include <memory>
+
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
@@ -72,7 +74,7 @@
pthread_t thread;
// Thread data.
- log_reader_thread_data* data = new log_reader_thread_data();
+ std::unique_ptr<log_reader_thread_data> data = std::make_unique<log_reader_thread_data>();
data->service = service;
// Create the thread
@@ -86,11 +88,15 @@
pthread_attr_destroy(&attr);
return err;
}
- err = pthread_create(&thread, &attr, log_reader_thread_func, static_cast<void*>(data));
+ err = pthread_create(&thread, &attr, log_reader_thread_func,
+ static_cast<void*>(data.get()));
if (err != NO_ERROR) {
pthread_attr_destroy(&attr);
return err;
}
+ // Release here rather than in pthread_create, since an error creating the
+ // thread leaves `data` ownerless.
+ data.release();
pthread_attr_destroy(&attr);
return NO_ERROR;