Skip to content

Lint for returning raw pointers to temporary stack locations that don't outlive the statement that creates them #10959

@sdroege

Description

@sdroege

What it does

The general pattern of the code this should complain about is something like

let x = &(some expression that is stored in a temporary variable on the stack) as *const T;

Similar with using addr_of! instead of & and casts, etc.

Concrete examples this would catch are

let x = &(1 + 2) as *const i32;
let x = &(x as *const i32) as *const *const i32;

In both cases the part in the parenthesis is stored in a temporary stack location that is no longer valid after the whole statement.

It should however not catch

let x = &(*ptr).x as *const T;
let x = &(some_variable) as *const T;

Advantage

Whatever pointer is created there is pointing to no longer valid stack memory, so any usage afterwards will be unsound

Drawbacks

Theoretically this could cause false positives but the only case I can see where the resulting code is not unsound is if you cast the pointer to an usize and do some calculations with it. I don't see how that could lead to any useful results in such a context though.

Example

See examples above

Metadata

Metadata

Assignees

Labels

A-lintArea: New lints

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions