In this section:
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.
|
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); } |
[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, |
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
.
The table below shows Common Weakness Enumerations associated with this error.
CWE | Description |
---|---|
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 |