Skip to content

[C++] ArraySpan::FillFromScalar is unsafe #35581

@bkietz

Description

@bkietz

Describe the bug, including details regarding any error messages, version, and platform.

ArraySpan::FillFromScalar can store pointers into the structure itself (specifically, into ArraySpan::scratch_space) which produces an ArraySpan which easily be unsafely moved and copied:

ArraySpan span;
span.FillFromScalar(scalar);

UseSpan(span); // Fine; the original span is still alive.

return span; // Undefined Behavior; the returned copy views
             // a stack variable whose lifetime has ended.

The capability to view a Scalar as an ArraySpan can be preserved and made safer by restricting access to the span to an explicitly delineated scope:

ArraySpan::FillFromScalar(scalar, [&](ArraySpan span) {
  UseSpan(span); // Fine; the viewed scratch space is alive inside this scope.
});

This has the pleasant side effect of reducing the size of ArraySpan by 16 bytes.

Component(s)

C++

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions