<table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Issue</th>
<td>
<a href=https://github.com/llvm/llvm-project/issues/81734>81734</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
[clang] False positive clang-analyzer-core.DivideZero with loop over container
</td>
</tr>
<tr>
<th>Labels</th>
<td>
clang
</td>
</tr>
<tr>
<th>Assignees</th>
<td>
</td>
</tr>
<tr>
<th>Reporter</th>
<td>
chrchr-github
</td>
</tr>
</table>
<pre>
~~~c++
#include <vector>
int f(const std::vector<int>& v) {
if (v.empty())
return 0;
int h = 0;
for (auto it = v.begin(); it != v.end(); ++it) {
h = std::max(h, *it);
}
int x = 512;
if (h < x)
h = h * (x / h + 1);
return h;
}
~~~
~~~
<source>:12:20: warning: Division by zero [clang-analyzer-core.DivideZero]
12 | h = h * (x / h + 1);
| ~~^~~
<source>:3:9: note: Assuming the condition is false]
3 | if (v.empty())
| ^~~~~~~~~
<source>:3:5: note: Taking false branch]
3 | if (v.empty())
| ^
<source>:5:5: note: 'h' initialized to 0
5 | int h = 0;
| ^~~~~
<source>:6:5: note: Loop condition is false. Execution continues on line 10
6 | for (auto it = v.begin(); it != v.end(); ++it) {
| ^
<source>:11:9: note: 'h' is < 'x'
11 | if (h < x)
| ^
<source>:11:5: note: Taking true branch
11 | if (h < x)
| ^
<source>:12:20: note: Division by zero
12 | h = h * (x / h + 1);
| ~~^~~
~~~
There could be division by zero if the vector holds only numbers <= 0. However, the diagnostic seems to imply that the vector might be empty, which is impossible.
https://godbolt.org/z/cbKh7axxd
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJy0VkGP4jgT_TXFpdQoqRACBw40NPqkb49z2pvjmNi7jo1sh4Y-8NtXdhhoss3MrkZrRXJil-u9Ktezw7xXrRFiBeUrlNsJ64O0bsWl49K9tCrIvp7UtjmvLpcLB3qNT7aFbA1UKMN13wiEYnMUPFgHxdswqUzAPdCCW-MD-tBAsYZi_d1qo0yItjTHI9ASobo6RURUewRaHKeiO4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