In this section:
Overview
This error is generated when any of the following occur:
- A memory block is allocated with
new
and freed withfree
. - A memory block is allocated with
malloc
and freed withdelete
. - A memory block is allocated with one heap and freed with another heap.
Memory was allocated with Memory was allocated with Memory is allocated by one heap and freed by a different heap Code Description Enabled Reported ALLOC_CONFLICT Mixing malloc/free with new/ delete Runtime (badfree) new
or new[]
and an attempt was made to free it with free
.Runtime (baddelet) malloc
and an attempt was made to free it with delete
or delete[]
.Runtime (badhandle) Runtime new
and delete
with malloc
and free
, but this is not good programming practice and may affect portability.
Problem 1
The following code shows a typical example of allocating a block of memory with new
and then freeing it with free
, instead of delete
.
/* * File: alloc1.cpp */ #include <stdlib.h> int main() { char *a; a = new char; free(a); return 0; }
Diagnosis at Runtime
[alloc1.cpp:10] **ALLOC_CONFLICT** >> free(a); Memory allocation conflict: a ---- Associated Common Weakness Enumerations ---- CWE-762: Mismatched memory management routines CWE-763: Release of invalid pointer or reference free() used to deallocate memory which was allocated using new a, allocated at: main()alloc1.cpp, 9 Stack trace where the error occurred: main()alloc1.cpp, 10
- Line 2: Source line at which the problem was detected.
- Line 3: Brief description of the problem.
- Lines 5-7: CWEs associated with this problem.
- Line 9: Description of the conflicting allocation/deallocation.
- Line 14: Stack trace showing the function call sequence leading to the error.
Problem 2
The following code shows another typical example of this type of error, allocating a block of memory with malloc
and then freeing it with delete
.
/* * File: alloc2.cpp */ #include <stdlib.h> int main() { char *a; a = (char *) malloc(1); delete a; return 0; }
Diagnosis at Runtime
[alloc2.cpp:10] **ALLOC_CONFLICT** >> delete a; Memory allocation conflict: a ---- Associated Common Weakness Enumerations ---- CWE-762: Mismatched memory management routines CWE-763: Release of invalid pointer or reference delete operator used to deallocate memory not allocated by new block allocated at: malloc()(interface) main()alloc2.cpp, 9 Stack trace where the error occurred: main()alloc2.cpp, 10
- Line 2: Source line at which the problem was detected.
- Line 3: Brief description of the problem.
- Lines 5-7: CWEs associated with the problem
- Line 9: Description of the conflicting allocation/deallocation.
- Line 14: Stack trace showing the function call sequence leading to the error.
Repair
This type of error can be corrected by making sure that all your memory allocations match up.
References
The table below shows Common Weakness Enumerations associated with this error.