Skip to content

Commit 4aa91a2

Browse files
committed
Improve handling of buffer
1 parent fa82549 commit 4aa91a2

File tree

1 file changed

+9
-8
lines changed

1 file changed

+9
-8
lines changed

examples/common.cpp

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
#define WIN32_LEAN_AND_MEAN
1919
#define NOMINMAX
2020
#include <windows.h>
21+
#include <intrin.h>
2122
#include <fcntl.h>
2223
#include <io.h>
2324
#define CP_UTF8 65001
@@ -53,14 +54,13 @@ int32_t get_num_physical_cores() {
5354
return num_physical_cores;
5455
}
5556
#elif defined(_WIN32)
56-
SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *buffer = nullptr;
57-
DWORD length = 0;
58-
5957
// Call GetLogicalProcessorInformationEx with a nullptr buffer to get the required buffer length
58+
DWORD length = 0;
6059
GetLogicalProcessorInformationEx(RelationAll, nullptr, &length);
6160

6261
// Allocate memory for the buffer
63-
buffer = reinterpret_cast<SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *>(new char[length]);
62+
std::unique_ptr<char[]> buffer_ptr(new char[length]);
63+
char* buffer = buffer_ptr.get();
6464

6565
// Things to count
6666
unsigned int physical_cores = 0;
@@ -71,11 +71,14 @@ int32_t get_num_physical_cores() {
7171
unsigned int logical_efficiency_cores = 0;
7272

7373
// Call GetLogicalProcessorInformationEx again with the allocated buffer
74-
if (GetLogicalProcessorInformationEx(RelationAll, buffer, &length)) {
74+
if (GetLogicalProcessorInformationEx(
75+
RelationAll,
76+
reinterpret_cast<SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *>(buffer),
77+
&length)) {
7578
DWORD offset = 0;
7679

7780
while (offset < length) {
78-
auto info = reinterpret_cast<SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *>(reinterpret_cast<char *>(buffer) + offset);
81+
auto info = reinterpret_cast<SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *>(buffer + offset);
7982

8083
if (info->Relationship == RelationProcessorCore) {
8184
physical_cores += info->Processor.GroupCount;
@@ -111,8 +114,6 @@ int32_t get_num_physical_cores() {
111114
fprintf(stderr, "Failed to get processor information. Error: %u\n", GetLastError());
112115
}
113116

114-
delete[] buffer;
115-
116117
if (physical_performance_cores > 0) {
117118
return static_cast<int32_t>(physical_performance_cores);
118119
} else if (physical_cores > 0) {

0 commit comments

Comments
 (0)