In this section:
Overview
This error is generated whenever a function returns a pointer to a block of memory which is then ignored by the calling routine. In this case, the allocated memory block is permanently lost and can never be freed.
Code | Description | Enabled | Reported | Platform |
---|---|---|---|---|
LEAK_RETURN | Memory leaked leaving scope | Runtime | Windows/Unix |
Problem
The following code calls the function gimme
, which allocates a memory block that is never freed.
/* * File: leakscop.c */ #include <stdlib.h> void gimme() { char *p; p = malloc(10); return; } main() { gimme(); return (0); }
Diagnosis at Runtime
[leakscop.c:10] **LEAK_SCOPE** >> return; Memory leaked leaving scope: <return> ---- Associated Common Weakness Enumerations ---- CWE-119: Improper Restriction of Operations within the Bounds of a Memory Buffer CWE-400: Uncontrolled resource consumption CWE-401: Missing release of memory after effective lifetime CWE-772: Missing release of resource after effective lifetime Lost block: 0x0003870 thru 0x00013879 (10 bytes) block allocated at: malloc() (interface) gimme() leakscop.c, 9 main() leakscop.c, 15 Stack trace where the error occurred: gimme() leakscop.c,
- Line 2: Source file and line at which the problem was detected.
- Line 3: Description of the problem and the block that is to be lost.
- Line 5-9: CWEs associated with this problem.
- Line 11: Description of the block of memory that is about to be lost, including its size and the line number at which it was allocated.
- Line 16: Stack trace showing the function call sequence leading to the error.
Repair
This problem usually results from an oversight on the part of the programmer and is cured by simply freeing a block before returning from a routine. In the current example, a call to free(p)
before line 10 would cure the problem.
An easy way to generate this error is to return from the middle of a routine, possibly due to an error condition arising, without freeing previously allocated data. This bug is easy to introduce when modifying existing code.
Some applications may be unable to free memory blocks and may not need to worry about their permanent loss. To suppress these error messages in this case, suppress LEAK_SCOPE
.
References
The table below shows Common Weakness Enumerations associated with this error.