In this section:
Overview
This error is generated whenever an expression tries to compute the difference between pointers that do not point into the same memory block. The ANSI C language specification declares this construct undefined except in the special case where a pointer points to an object one past the end of a block.
Expression subtracts unrelated pointersCode Description Enabled Reported Platform EXPR_UNRELATED_PTRDIFF Runtime Windows/Unix
Problem
The following code illustrates the problem by subtracting two pointers to different data objects.
/* * File: expudiff.c */ #include <stdlib.h> main() { char a[10], *b; int d; b = (char *)malloc(10); d = b - a; return (0); }
Diagnosis at Runtime
[expudiff.c:12] **EXPR_UNRELATED_PTRDIFF** >> d = b - a; Expression subtracts unrelated pointers: b - a ---- Associated Common Weakness Enumerations ---- CWE-119: Improper Restriction of Operations within the Bounds of a Memory Buffer Left hand side : 0x00013878 In block : 0x00013878 thru 0x00013881 (10 bytes) b, allocated at: malloc() (interface) main() expudiff.c, 11 Right hand side : 0xf7fffb8c In block : 0xf7fffb8c thru 0xf7fffb95 (10 bytes) a, declared at expudiff.c, 8 Stack trace where the error occurred: main() expudiff.c, 12
- 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-6: CWE associated with the problem.
- Line 9: Description of the two pointers involved in the expression. For each pointer the associated block of memory is shown together with its size and the line number at which it was declared or allocated.
- Line 16: Stack trace showing the function call sequence leading to the error.
Repair
While this construct is undefined according to the ANSI C language specification, it is supported on many machines and its use is fairly common practice. If your application genuinely needs to use this construct, you can suppress error messages by suppressing EXPR_UNRELATED_PTRDIFF
in the Suppressions Control Panel.
References
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 |