In this section:

Overview

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.

CodeDescriptionEnabledReportedPlatform
LEAK_ASSIGN

Memory leaked as a result of pointer reassignment

(tick)RuntimeWindows/Unix


Problem

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);
}

Diagnosis at Runtime

[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
  • Line 2: Source file and line at which the problem was detected.
  • Line 3: Description of the problem and the expression that is in error.
  • 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 15: Stack trace showing the function call sequence leading to the error.

Repair

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.

References

The table below shows Common Weakness Enumerations associated with this error.

CWEDescription
CWE-119Improper Restriction of Operations within the Bounds of a Memory Buffer
CWE-400Uncontrolled resource consumption
CWE-401Missing release of memory after effective lifetime
CWE-772Missing release of resource after effective lifetime
  • No labels