In this section:
Overview
This problem occurs when an attempt is made to dereference a pointer that points to a block of memory that has been freed.
Code | Description | Enabled | Reported | Platform |
---|---|---|---|---|
READ_DANGLING | Reading from a dangling pointer | Runtime | Windows/Unix |
Problem
The following code attempts to use a piece of dynamically allocated memory after it has already been freed.
/* * File: readdngl.c */ # include <stdlib.h> main() { char b; char *a = (char *)malloc(10); free(a); b = *a; return (0); }
Diagnosis at Runtime
[readdngl.c:12] **READ_DANGLING** >> b = *a; Reading from a dangling pointer: a ---- Associated Common Weakness Enumerations ---- CWE-119: Improper Restriction of Operations within the Bounds of a Memory Buffer CWE-416: Use after free CWE-825: Expired pointer dereference Pointer: 0x000173e8 In block: 0x000173e8 thru 0x000173f1 (10 bytes) block allocated at: malloc() (interface) main() readdngl.c, 9 stack trace where memory was freed: main() readdngl.c, 11 Stack trace where the error occurred: main() readdngl.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 5-8: CWEs associated with the problem.
- Line 10: Value of the dangling pointer variable.
- Line 11: Description of the block to which this pointer used to point, including its size, name and the line at which it was allocated.
- Line 15: Stack trace showing where this block was freed.
- Line 17: Stack trace showing the function call sequence leading to the error.
Repair
Check that the de-allocation that occurs at the indicated location should, indeed, have taken place. Also check that the pointer you are using should really be pointing to a block allocated at the indicated place.
References
The table below shows Common Weakness Enumerations associated with this error.