Main Content

Mismatched alloc/dealloc functions on Windows

Improper deallocation function causes memory corruption issues

Description

This defect occurs when you use a Windows® deallocation function that is not properly paired to its corresponding allocation function.

Risk

Deallocating memory with a function that does not match the allocation function can cause memory corruption or undefined behavior. If you are using an older version of Windows, the improper function can also cause compatibility issues with newer versions.

Fix

Properly pair your allocation and deallocation functions according to the functions listed in this table.

Allocation FunctionDeallocation Function
malloc()free()
realloc()free()
calloc()free()
_aligned_malloc()_aligned_free()
_aligned_offset_malloc()_aligned_free()
_aligned_realloc()_aligned_free()
_aligned_offset_realloc()_aligned_free()
_aligned_recalloc()_aligned_free()
_aligned_offset_recalloc()_aligned_free()
_malloca()_freea()
LocalAlloc()LocalFree()
LocalReAlloc()LocalFree()
GlobalAlloc()GlobalFree()
GlobalReAlloc()GlobalFree()
VirtualAlloc()VirtualFree()
VirtualAllocEx()VirtualFreeEx()
VirtualAllocExNuma()VirtualFreeEx()
HeapAlloc()HeapFree()
HeapReAlloc()HeapFree()

Examples

expand all

#ifdef _WIN32_
#include <windows.h>
#else
#define _WIN32_
typedef void *HANDLE;
typedef HANDLE HGLOBAL;
typedef HANDLE HLOCAL;
typedef unsigned int UINT;
extern HLOCAL LocalAlloc(UINT uFlags, UINT uBytes);
extern HLOCAL LocalFree(HLOCAL hMem);
extern HGLOBAL GlobalFree(HGLOBAL hMem);
#endif

#define SIZE9 9


void func(void)
{
	/* Memory allocation */
    HLOCAL p = LocalAlloc(0x0000, SIZE9);
	
    if (p) {
		/* Memory deallocation. */
        GlobalFree(p);
		
    }
}
     
      

In this example, memory is allocated with LocallAlloc(). The program then erroneously uses GlobalFree() to deallocate the memory.

Correction — Properly Pair Windows Allocation and Deallocation Functions

When you allocate memory with LocalAllocate(), use LocalFree() to deallocate the memory.

#ifdef _WIN32_
#include <windows.h>
#else
#define _WIN32_
typedef void *HANDLE;
typedef HANDLE HGLOBAL;
typedef HANDLE HLOCAL;
typedef unsigned int UINT;
extern HLOCAL LocalAlloc(UINT uFlags, UINT uBytes);
extern HLOCAL LocalFree(HLOCAL hMem);
extern HGLOBAL GlobalFree(HGLOBAL hMem);
#endif

#define SIZE9 9
void func(void)
{
	/* Memory allocation */
    HLOCAL p = LocalAlloc(0x0000, SIZE9);
    if (p) {
		/* Memory deallocation. */
        LocalFree(p);  
    }
} 

Result Information

Group: Dynamic memory
Language: C | C++
Default: Off
Command-Line Syntax: WIN_MISMATCH_DEALLOC
Impact: Low

Version History

Introduced in R2017b