Skip to content

[Code scan] Bound-check Tensor::inner_most_ptr for rank-1 and one-past indices #7560

Description

@njzjz

This issue is a result of a Codex global repository scan.

Tensor::inner_most_ptr() is documented as supporting tensors with rank <= 2, but its bounds check has two issues:

  • index == dim_size is accepted because the check uses > instead of >=, returning a one-past pointer.
  • For rank-1 tensors, it evaluates shape_.dim_size(shape_.ndim() - 2) before the rank-1 branch, which underflows the dimension expression.

template <typename T>
T* inner_most_ptr(const int &index) const {
if (shape_.ndim() > 2) {
throw std::invalid_argument("Invalid call, inner_most_ptr only support tensor rank <= 2!");
}
if (index > shape_.dim_size(static_cast<int>(shape_.ndim() - 2))) {
throw std::invalid_argument("Invalid index, index of the inner-most must less than the inner-most shape size!");
}
if (shape_.ndim() == 1) {
return data<T>() + index;
}
return data<T>() + index * shape_.dim_size(static_cast<int>(shape_.ndim()) - 1);

Relevant code:

if (index > shape_.dim_size(static_cast<int>(shape_.ndim() - 2))) {
    throw std::invalid_argument(...);
}
if (shape_.ndim() == 1) {
    return data<T>() + index;
}
return data<T>() + index * shape_.dim_size(static_cast<int>(shape_.ndim()) - 1);

Suggested fix:

Reject rank 0, choose the bound from shape_.dim_size(0) for rank 1 and rank 2 row access, and check index < 0 || index >= bound before returning a pointer.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    Status
    Todo

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions