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 WRITE_DANGLING Writing to 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: writdngl.c */ #include <stdlib.h> main() { char *a = (char *)malloc(10); free(a); *a = 'x'; return (0); }
Diagnosis at Runtime
[writdngl.c:11] **WRITE_DANGLING** >> *a = 'x'; Writing to 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() writdngl.c, 8 Stack trace where memory was freed: main() writdngl.c, 10 Stack trace where the error occurred: main() writdngl.c, 11 **Memory corrupted. Program may crash!!**
- 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 this 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: Indication of the line at which 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.