In this section:
Overview
This error is generated whenever an expression operates on a dangling pointer, .e., one that points to either:
- A block of dynamically allocated memory that has already been freed.
- A block of memory which was allocated on the stack in some routine that has subsequently returned.
Expression uses a dangling pointerCode Description Enabled Reported Platform EXPR_DANGLING Runtime Windows/Unix
Problem
In the following code, a block of memory is allocated and freed. After the memory is de-allocated, the pointer is used again even though it no longer points to valid memory.
* * File: expdangl.cpp */ #include <stdlib.h> main() { char *a = (char *)malloc(10); char b[10]; free(a); if(a > b) a = b; return (0); }
Diagnosis at Runtime
[expdangl.c:12] **EXPR_DANGLING** >> if(a > b) Expression uses dangling pointer: a > b Pointer : 0x00013868 In block : 0x00013868 thru 0x00013871 (10 bytes) block allocated at: malloc() (interface) main() expdangl.c, 8 stack trace where memory was freed: main() expdangl.c, 11 Stack trace where the error occurred: main() expdangl.c, 12
- Line 2: Source line at which the problem was detected.
- Line 3: Description of the problem and the expression that is in error.
- Line 4: Description of the memory block to which the pointer used to point, including the location at which it was allocated and subsequently freed.
- Line 11: Stack trace showing the function call sequence leading to the error.
Repair
A good first check is to see if the pointer used in the expression at the indicated line is actually the one intended. If it appears to be the correct pointer, check the line of code where the block was freed (as shown in the error message) to see if it was freed incorrectly.