From d25b58f7eab819945deaecabdd99b6ac3c22a3fb Mon Sep 17 00:00:00 2001 From: PhyxionNL <7643972+PhyxionNL@users.noreply.github.com> Date: Tue, 22 Jun 2021 16:43:13 +0200 Subject: [PATCH] Always free allocated memory in FirmwareTable --- .../Hardware/FirmwareTable.cs | 55 +++++++++++++------ 1 file changed, 38 insertions(+), 17 deletions(-) diff --git a/LibreHardwareMonitorLib/Hardware/FirmwareTable.cs b/LibreHardwareMonitorLib/Hardware/FirmwareTable.cs index f73070a..6ab8dc4 100644 --- a/LibreHardwareMonitorLib/Hardware/FirmwareTable.cs +++ b/LibreHardwareMonitorLib/Hardware/FirmwareTable.cs @@ -35,17 +35,26 @@ namespace LibreHardwareMonitor.Hardware return null; - IntPtr nativeBuffer = Marshal.AllocHGlobal(size); - Interop.Kernel32.GetSystemFirmwareTable(provider, table, nativeBuffer, size); + IntPtr allocatedBuffer = IntPtr.Zero; - if (Marshal.GetLastWin32Error() != 0) - return null; + try + { + allocatedBuffer = Marshal.AllocHGlobal(size); + + Interop.Kernel32.GetSystemFirmwareTable(provider, table, allocatedBuffer, size); + if (Marshal.GetLastWin32Error() != 0) + return null; - byte[] buffer = new byte[size]; - Marshal.Copy(nativeBuffer, buffer, 0, size); - Marshal.FreeHGlobal(nativeBuffer); - return buffer; + byte[] buffer = new byte[size]; + Marshal.Copy(allocatedBuffer, buffer, 0, size); + return buffer; + } + finally + { + if (allocatedBuffer != IntPtr.Zero) + Marshal.FreeHGlobal(allocatedBuffer); + } } public static string[] EnumerateTables(Interop.Kernel32.Provider provider) @@ -61,17 +70,29 @@ namespace LibreHardwareMonitor.Hardware return null; } - IntPtr nativeBuffer = Marshal.AllocHGlobal(size); - Interop.Kernel32.EnumSystemFirmwareTables(provider, nativeBuffer, size); - byte[] buffer = new byte[size]; - Marshal.Copy(nativeBuffer, buffer, 0, size); - Marshal.FreeHGlobal(nativeBuffer); + IntPtr allocatedBuffer = IntPtr.Zero; - string[] result = new string[size / 4]; - for (int i = 0; i < result.Length; i++) - result[i] = Encoding.ASCII.GetString(buffer, 4 * i, 4); + try + { + allocatedBuffer = Marshal.AllocHGlobal(size); - return result; + Interop.Kernel32.EnumSystemFirmwareTables(provider, allocatedBuffer, size); + + byte[] buffer = new byte[size]; + Marshal.Copy(allocatedBuffer, buffer, 0, size); + + string[] result = new string[size / 4]; + + for (int i = 0; i < result.Length; i++) + result[i] = Encoding.ASCII.GetString(buffer, 4 * i, 4); + + return result; + } + finally + { + if (allocatedBuffer != IntPtr.Zero) + Marshal.FreeHGlobal(allocatedBuffer); + } } } }