# error[E0515]: cannot return value referencing local variable `x`

- **ID:** `rust/e0515-cannot-return-value-referencing-local-variable`
- **Domain:** rust
- **Category:** type_error
- **Error Code:** `E0515`
- **Verification:** ai_generated
- **Fix Rate:** 90%

## Root Cause

Returning a reference to a local variable that will be dropped when the function exits, creating a dangling pointer.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| rustc 1.75.0 | active | — | — |
| rustc 1.78.0 | active | — | — |
| rustc 1.80.0 | active | — | — |

## Workarounds

1. **Return the owned value instead of a reference. Example: fn create() -> String { let s = String::from("hello"); s }** (95% success)
   ```
   Return the owned value instead of a reference. Example: fn create() -> String { let s = String::from("hello"); s }
   ```
2. **Accept a reference parameter and write into it instead of returning a reference. Example: fn fill(buf: &mut String) { buf.push_str("hello"); }** (90% success)
   ```
   Accept a reference parameter and write into it instead of returning a reference. Example: fn fill(buf: &mut String) { buf.push_str("hello"); }
   ```
3. **Use an arena allocator or a reference-counted pointer like Rc<T> to extend the lifetime. Example: Rc::new(local_var)** (85% success)
   ```
   Use an arena allocator or a reference-counted pointer like Rc<T> to extend the lifetime. Example: Rc::new(local_var)
   ```

## Dead Ends

- **** — Box::leak converts a Box to a 'static reference, but the local variable is still on the stack and will be dropped. The reference becomes dangling. (90% fail)
- **** — Transmuting lifetimes doesn't change the fact that the local variable is dropped. The reference becomes invalid immediately upon return. (95% fail)
- **** — Raw pointers don't have lifetime checks, but the data is still deallocated when the function returns, creating a dangling pointer. (80% fail)
