flagging unsigned subtraction assigned to bigger signed number?
Richard (Rikki) Andrew Cattermole
richard at cattermole.co.nz
Wed May 21 05:13:59 UTC 2025
On 21/05/2025 4:44 PM, Walter Bright wrote:
> This is a common issue. Unfortunately, nobody has come up with a
> solution to this in the last 45 years. Since every combination of signed
> and unsigned has well-defined behavior, prohibiting one of those
> behaviors is going to break a lot of code. Changing the conversion rules
> will break a lot of existing behavior. There's no way around it.
``$ gcc --analyzer file.c``
```c++
#include <stdio.h>
void test(unsigned int len, int* ptr) {
for(int i = 0; i < len; i++) {
int j = i - 1;
printf("%d\n", ptr[j]);
}
}
int main() {
int val = 0;
test(1, &val);
return 0;
}
```
Some highlights of output (its a giant dump of awesomeness):
```
<source>:6:15: warning: stack-based buffer under-read [CWE-127]
[-Wanalyzer-out-of-bounds]
out-of-bounds read from byte -4 till byte -1 but 'val' starts at byte 0
```
Clang-analyzer doesn't appear to have a solution to this (yet), but
gcc's does appear to catch the obvious scenario here.
More information about the Digitalmars-d
mailing list