Skip to content

sign-conversion warning in catch_tostring.hpp #2545

@Teskann

Description

@Teskann

Describe the bug

Hello, the latest devel of Catch2 raises a warning on g++ 12.

conversion to ‘std::size_t’ {aka ‘long unsigned int’} from ‘long int’ may change the sign of the result

This warning was introduced a few days ago by PR #2540

File catch_tostring.hpp line 46:

inline std::size_t catch_strnlen(const char *str, std::size_t n) {
    auto ret = std::char_traits<char>::find(str, n, '\0');
    if (ret != nullptr) {
        return ret - str;  // <-- Here !
    }
    return n;
}

Expected behavior

Catch2 builds without warnings.

Reproduction steps

Build Catch2 with g++ .

Platform information:
g++ version 12.1.0 (Ubuntu 12.1.0-2ubuntu1~22.04)

Possible fixes

  • Change the return type of catch_strnlen to std::ptrdiff_t. This would prevent to return n without a cast to std::ptrdiff_t.
  • Explicitly cast the result to std::size_t.
return static_cast<std::size_t>(ret - str);

This should be relatively safe as str should never be greater than ret. In my opinion this is the way to go.

@rkaminsk what do you think ?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions