Skip to content

[BUG] array.h mixes signed and unsigned ints, causing potential issues #2993

@MillaFleurs

Description

@MillaFleurs

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.out

Expected 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

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