From 4aa91a230aa07c631b3b0d76cbb0a69c130cb808 Mon Sep 17 00:00:00 2001 From: Danny Daemonic Date: Tue, 2 May 2023 15:38:00 -0700 Subject: [PATCH] Improve handling of buffer --- examples/common.cpp | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/examples/common.cpp b/examples/common.cpp index d8aa95014..d8c77fcbd 100644 --- a/examples/common.cpp +++ b/examples/common.cpp @@ -18,6 +18,7 @@ #define WIN32_LEAN_AND_MEAN #define NOMINMAX #include +#include #include #include #define CP_UTF8 65001 @@ -53,14 +54,13 @@ int32_t get_num_physical_cores() { return num_physical_cores; } #elif defined(_WIN32) - SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *buffer = nullptr; - DWORD length = 0; - // Call GetLogicalProcessorInformationEx with a nullptr buffer to get the required buffer length + DWORD length = 0; GetLogicalProcessorInformationEx(RelationAll, nullptr, &length); // Allocate memory for the buffer - buffer = reinterpret_cast(new char[length]); + std::unique_ptr buffer_ptr(new char[length]); + char* buffer = buffer_ptr.get(); // Things to count unsigned int physical_cores = 0; @@ -71,11 +71,14 @@ int32_t get_num_physical_cores() { unsigned int logical_efficiency_cores = 0; // Call GetLogicalProcessorInformationEx again with the allocated buffer - if (GetLogicalProcessorInformationEx(RelationAll, buffer, &length)) { + if (GetLogicalProcessorInformationEx( + RelationAll, + reinterpret_cast(buffer), + &length)) { DWORD offset = 0; while (offset < length) { - auto info = reinterpret_cast(reinterpret_cast(buffer) + offset); + auto info = reinterpret_cast(buffer + offset); if (info->Relationship == RelationProcessorCore) { physical_cores += info->Processor.GroupCount; @@ -111,8 +114,6 @@ int32_t get_num_physical_cores() { fprintf(stderr, "Failed to get processor information. Error: %u\n", GetLastError()); } - delete[] buffer; - if (physical_performance_cores > 0) { return static_cast(physical_performance_cores); } else if (physical_cores > 0) {