Edit

Share via


Error: alloc-dealloc-mismatch

Address Sanitizer Error: Mismatch between allocation and deallocation APIs

Enables runtime detection of mismatched memory operations that may lead to undefined behavior, such as:

  • malloc must be paired with free, not delete or delete[].
  • new must be paired with delete, not free or delete[].
  • new[] must be paired with delete[], not delete or free.

In Windows, alloc-dealloc-mismatch error detection is off by default. To enable it, set the environment variable set ASAN_OPTIONS=alloc_dealloc_mismatch=1 before running your program.

Example

// example1.cpp
// Demonstrate alloc-dealloc-mismatch error
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char* argv[])
{
    if (argc != 2) return -1;

    switch (atoi(argv[1]))
    {
        case 1:
            delete[](new int[10]);
            break;
        case 2:
            delete (new int[10]);      // Boom!
            break;
        default:
            printf("arguments: 1: no error 2: runtime error\n");
            return -1;
    }
    return 0;
}

In a Visual Studio 2019 version 16.9 or later developer command prompt, run the following commands to see an exampe of alloc_dealloc_mismatch:

cl example1.cpp /fsanitize=address /Zi
set ASAN_OPTIONS=alloc_dealloc_mismatch=1
devenv /debugexe example1.exe 2

Output

Screenshot of debugger displaying alloc-dealloc-mismatch error in example 1.

See also

AddressSanitizer overview
AddressSanitizer known issues
AddressSanitizer build and language reference
AddressSanitizer runtime reference
AddressSanitizer shadow bytes
AddressSanitizer cloud or distributed testing
AddressSanitizer debugger integration
AddressSanitizer error examples