-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Closed
Description
Describe the bug
The following function adds a signed + unsigned number together without explicitly casting, causing potential issues.
// Line 108
/** The number of dimensions of the array. */
size_t ndim() const {
return array_desc_->shape.size();
}
// Line 118
/**
* Get the size of the corresponding dimension.
*
* This function supports negative indexing and provides
* bounds checking. */
auto shape(int dim) const {
return shape().at(dim < 0 ? dim + ndim() : dim);
}
To Reproduce
dim is signed ndim is unsigned so there's the possibility of unexpected behavior as the below code demonstrates.
// test.cpp
#include <cstdio>
#include <cstddef>
#include <limits>
#include <initializer_list>
int main() {
std::size_t ndim = 3;
for (int dim : {-1, -2, -3, -4}) {
std::size_t idx = (dim < 0) ? (ndim + dim) : static_cast<std::size_t>(dim);
std::printf("ndim=%zu dim=%d -> idx=%zu\n", ndim, dim, idx);
}
std::printf("SIZE_MAX=%zu\n", std::numeric_limits<std::size_t>::max());
return 0;
}
// compile and run using the following command:
// clang++ -std=c++20 -Wall -Wextra -Wsign-conversion test.cpp && ./a.outExpected behavior
This is a quick patch and I'm not sure why this wasn't caught in linting. As you can see if comiled with -Wall it comes up as a warning when this happens.
Desktop (please complete the following information):
- OS Version: Tahoe 26.2
Metadata
Metadata
Assignees
Labels
No labels