In this section:
This error is generated whenever a pointer assignment occurs which will prevent a block of dynamically allocated memory from ever being freed. Normally this happens because the pointer being changed is the only one that still points to the dynamically allocated block.
|
The following code allocates a block of memory then reassigns the pointer to the block to a static memory block. As a result, the dynamically allocated block can no longer be freed.
/*
* File: leakasgn.c
*/
#include <stdlib.h>
main()
{
char *b, a[10];
b = (char *)malloc(10);
b = a;
return (0);
} |
[leakasgn.c:11] **LEAK_ASSIGN** >> b = a; Memory leaked due to pointer reassignment: b ---- 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 : 0x0804b018 thru 0x0804b021 (10 bytes) b, allocated at leakasgn.c, 10 malloc() (interface) main() leakasgn.c, 10 Stack trace where the error occurred: main() leakasgn.c, 11 |
In many cases, this problem is caused by simply forgetting to free a previously allocated block of memory when a pointer is reassigned. For example, the leak in the example code can be corrected as follows:
b = (char *)malloc(10); free(b); b = a; |
Some applications may be unable to free memory blocks and may not need to worry about their permanent loss. To suppress these error messages, suppress LEAK_ASSIGN.
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 |