From 91497beb650250cef23e0b23fb53f78b797f2ae1 Mon Sep 17 00:00:00 2001 From: Dimitar Krastev Date: Sat, 25 May 2024 10:55:03 +0300 Subject: [PATCH] Simplified allocation of heap buffer during gateway fetch on win32. (#1402) --- Pcap++/src/PcapLiveDevice.cpp | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/Pcap++/src/PcapLiveDevice.cpp b/Pcap++/src/PcapLiveDevice.cpp index 605399c0a2..02d9f19111 100644 --- a/Pcap++/src/PcapLiveDevice.cpp +++ b/Pcap++/src/PcapLiveDevice.cpp @@ -16,6 +16,7 @@ #include #include #include +#include #if defined(_WIN32) // The definition of BPF_MAJOR_VERSION is required to support Npcap. In Npcap there are // compilation errors due to struct redefinition when including both Packet32.h and pcap.h @@ -982,16 +983,18 @@ void PcapLiveDevice::setDefaultGateway() { #if defined(_WIN32) ULONG outBufLen = sizeof (IP_ADAPTER_INFO); - uint8_t* buffer = new uint8_t[outBufLen]; - PIP_ADAPTER_INFO adapterInfo = reinterpret_cast(buffer); + std::vector buffer(outBufLen); + PIP_ADAPTER_INFO adapterInfo = reinterpret_cast(buffer.data()); DWORD retVal = 0; retVal = GetAdaptersInfo(adapterInfo, &outBufLen); - uint8_t* buffer2 = new uint8_t[outBufLen]; if (retVal == ERROR_BUFFER_OVERFLOW) - adapterInfo = reinterpret_cast(buffer2); - - retVal = GetAdaptersInfo(adapterInfo, &outBufLen); + { + buffer.resize(outBufLen); + // Repins the adapter info pointer to the vector data pointer as the vector might be reallocated during the resize. + adapterInfo = reinterpret_cast(buffer.data()); + retVal = GetAdaptersInfo(adapterInfo, &outBufLen); + } if (retVal == NO_ERROR) { @@ -1018,10 +1021,6 @@ void PcapLiveDevice::setDefaultGateway() { PCPP_LOG_ERROR("Error retrieving default gateway address"); } - - delete[] buffer; - // cppcheck-suppress uninitdata - delete[] buffer2; #elif defined(__linux__) std::ifstream routeFile("/proc/net/route"); std::string line;