Skip to content

release: pure functions returning owned memory no longer double free - #4248

Merged
BaseMax merged 1 commit into
mainfrom
fix-pure-heap-returns
Nov 25, 2026
Merged

BaseMax merged 1 commit into
mainfrom
fix-pure-heap-returns

Conversation

@BaseMax

@BaseMax BaseMax commented Nov 25, 2026

Copy link
Copy Markdown
Member

Fixes #4243.

Calling a pure function that returns a str twice with the same argument could free the same memory twice. pure became __attribute__((pure)) in C and memory(read) willreturn in LLVM, which lets the optimizer merge two calls into one; but each call returns a new string that the caller frees, so after the merge both temporaries pointed at the same allocation. str.Trim, str.Substr and str.Concat are pure, so plain input validation crashed (default backend, --backend=llvm, and C with clang).

  • Both backends now ask one shared rule, sm.PureAttrOk, before emitting those attributes: they are kept only when the return type is a plain scalar (numbers, bool, char, enums). A pure function returning str, a vector, a map, a struct or anything else that may own memory still compiles and keeps its purity checks, but its calls are never merged.
  • Sema already rejects a pure function that writes a global, writes through a parameter or calls something impure. It now also rejects a pure method that assigns to a field of this (E013, English and Persian messages). No std pure method does that today.

Tests: general/pure_heap_returns (en, fa) calls user and std pure functions returning str and Vector several times in one expression; errors/pure_write_this (en, fa) checks the new error; codegen_test and llvm_test check that str and Vector returns lose the attributes while int keeps them.

Verified on macOS arm64: both programs from the issue crash with 0.7.0 on all three backends and print true / done with this branch.

…ptimizer merge calls; pure methods cannot write this
@BaseMax
BaseMax requested a review from a team as a code owner November 25, 2026 21:16
@BaseMax
BaseMax merged commit 3fc08d2 into main Nov 25, 2026
15 checks passed
@BaseMax
BaseMax deleted the fix-pure-heap-returns branch November 25, 2026 21:16
@coderabbitai

coderabbitai Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Explain Change →

Caution

Review failed

The pull request is closed.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@BaseMax BaseMax mentioned this pull request Nov 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Double free crash: pure functions returning str (even str.Trim) can kill your program

1 participant