Bug 113786 - cppcheck: return value from find_if not properly checked ?
Summary: cppcheck: return value from find_if not properly checked ?
Alias: None
Product: gcc
Classification: Unclassified
Component: c++ (show other bugs)
Version: 14.0
: P3 enhancement
Target Milestone: ---
Assignee: Not yet assigned to anyone
Keywords: diagnostic
Depends on:
Blocks: new-warning, new_warning cppcheck
  Show dependency treegraph
Reported: 2024-02-06 13:07 UTC by David Binderman
Modified: 2024-02-07 08:29 UTC (History)
2 users (show)

See Also:
Known to work:
Known to fail:
Last reconfirmed:


Note You need to log in before you can comment on or make changes to this bug.
Description David Binderman 2024-02-06 13:07:21 UTC
Consider the following newish C++ code:

#include <algorithm>
#include <array>
#include <iostream>
int main()
    auto is_even = [](int i) { return i % 2 == 0; };
    for (auto const& w : {std::array{3, 1, 4}, {1, 3, 5}})
        if (std::find_if(begin(w), end(w), is_even))
            std::cout << "w contains an even number " << '\n';
            std::cout << "w does not contain even numbers\n"; 

Here is static analyser cppcheck finding the problem with the find_if:

bug1003.cc:11:13: warning: Suspicious condition. The result of find() is an iterator, but it is not properly checked. [stlIfFind]

Recent Gcc and clang have little to say:

Alphasrc $ ~/gcc/results/bin/g++ -g -O2 -Wall -Wextra -pedantic -D_FORTIFY_SOURCE=3 bug1003.cc
Alphasrc $ ~/llvm/results/bin/clang++ -g -O2 -Wall -Wextra -pedantic -D_FORTIFY_SOURCE=3 bug1003.cc
Alphasrc $ 

I guess any C++ STL function that returns something non-zero (in this case end(w) )
on error is liable to this problem.

I found this problem in the source code of flang, the clang Fortran compiler,
so it does occur in practice.
Comment 1 Jonathan Wakely 2024-02-06 16:20:52 UTC
I guess we could put [[gnu::returns_nonnull]] on those functions, but it wouldn't help due to PR 86879.

This feels like something that belongs to static analysers, not a compiler.