Esc

defer_in_loop

Finds a defer in a loop body that cleans up something from outside the loop.

Category suspicious, warn by default.

Example
#import "Basic";

main :: () {
    buffer := alloc(64);
    names := string.["a", "b", "c"];

    for names {
        defer free(buffer);
        print("%\n", it);
    }
}
Diagnostic
warning[defer_in_loop]: this `defer` runs at the end of every iteration, not when the procedure returns
  --> example.jai:8:9
   |
 8 |         defer free(buffer);
   |         ^^^^^^^^^^^^^^^^^^
   |
   = help: move it before the loop if it should run once
   = note: `defer_in_loop` is `warn` by default
Fixed
#import "Basic";

main :: () {
    buffer := alloc(64);

    defer free(buffer);

    names := string.["a", "b", "c"];

    for names {
        print("%\n", it);
    }
}

The loop body's scope ends every iteration, so defer free(buffer) frees an outer buffer after the first pass.