llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

False positive divide by zero

Open llvmbot opened this issue 7 years ago • 4 comments

Bugzilla Link 41452
Version 7.0
OS Linux
Reporter LLVM Bugzilla Contributor
CC @devincoughlin,@Szelethus

Extended Description

The code:

read_n.c

#include <unistd.h>

ssize_t read_n(void *p, size_t size, size_t n) {
    size_t len = n * size;
    if (size && len / size != n) return 0;
    return len ? read(0, p, len) / size : 0;
}

The output:

$ clang-7 -Wall --analyze -c read_n.c
read_n.c:7:34: warning: Division by zero
    return len ? read(0, p, len) / size : 0;
                 ~~~~~~~~~~~~~~~~^~~~~~
1 warning generated.

Extra info (from Xcode - How can I get this from clang?) Assuming 'size' is 0 Assuming 'len' is not 0

But, if size is 0, len will also be 0.

llvmbot avatar Apr 10 '19 14:04 llvmbot

Hi!

Well, you would need to use from frontend flags too, thats the only option as of now. Those aren't guaranteed to be stable in between different versions of clang though.

$ clang-7 -Wall --analyze -c read_n.c -Xclang -analyzer-output=text
warning: Division by zero
    return len ? read(0, p, len) / size : 0;
                 ~~~~~~~~~~~~~~~~^~~~~~
note: Assuming 'size' is 0
    if (size && len / size != n) return 0;
        ^~~~
note: Left side of '&&' is false
    if (size && len / size != n) return 0;
             ^
note: Assuming 'len' is not equal to 0
    return len ? read(0, p, len) / size : 0;
           ^~~
note: '?' condition is true
note: Division by zero
    return len ? read(0, p, len) / size : 0;
                 ~~~~~~~~~~~~~~~~^~~~~~

Szelethus avatar Apr 17 '19 21:04 Szelethus

assigned to @devincoughlin

llvmbot avatar Apr 10 '19 14:04 llvmbot

no warning since since db28e48d67e3(https://github.com/llvm/llvm-project/pull/209048)

https://godbolt.org/z/8fdcfo1q4

hongtaihu avatar Oct 16 '26 04:10 hongtaihu

6. no warning since since db28e48(#209048) https://godbolt.org/z/8fdcfo1q4

Even though this issue is before the GitHub migration it has a motivating example which makes it easier to understand the context. Since https://github.com/llvm/llvm-project/pull/209048 resolved the underlying issue I close this as completed.

For the detailed discussion covering this issue you can visit my comment in the discussion thread on Discord: https://discord.com/channels/636084430946959380/1560968662943273062/1564402374926139602

benedekaibas avatar Oct 28 '26 21:10 benedekaibas