Skip to content

Commit 9299c78

Browse files
committed
Detect when a slice on the stack is accidentally returned from a function.
1 parent e1a125e commit 9299c78

File tree

3 files changed

+17
-0
lines changed

3 files changed

+17
-0
lines changed

releasenotes.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,7 @@
108108
- Add deprecation for `@param foo "abc"`.
109109
- Add `--header-output` and `header-output` options for controlling header output folder.
110110
- Generic faults is disallowed.
111+
- Detect when a slice on the stack is accidentally returned from a function.
111112

112113
### Fixes
113114
- Assert triggered when casting from `int[2]` to `uint[2]` #2115

src/compiler/sema_stmts.c

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -600,6 +600,13 @@ INLINE bool sema_check_not_stack_variable_escape(SemaContext *context, Expr *exp
600600
Expr *outer = expr;
601601
expr = sema_dive_into_expression(expr);
602602
bool allow_pointer = false;
603+
if (expr_is_const_slice(expr) && expr->const_expr.slice_init)
604+
{
605+
RETURN_SEMA_ERROR(outer, "A slice literal is backed by a stack allocated array which will be invalid once the function returns. "
606+
"However, you can place the literal in a global or 'static' variable and safely return that value as long "
607+
"as the caller of the function won't modify the slice.");
608+
609+
}
603610
// We only want && and &
604611
if (expr->expr_kind == EXPR_SUBSCRIPT_ADDR)
605612
{
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import std;
2+
fn int[] hello()
3+
{
4+
return { 1, 2 }; // #error: will be invalid
5+
}
6+
fn void main()
7+
{
8+
hello();
9+
}

0 commit comments

Comments
 (0)