Start by not capturing `elements` in: (index.with_length length).sort do (a, b: int) -> int: elements[a].cmp elements[b] Run
And in general it helps to know the language. For example `cast[ptr UncheckedArray[T]](cast[pointer](alloc(n * sizeof(T))))` should be `cast[ptr UncheckedArray[T]](alloc(n * sizeof(T)))` Also, a compiler error message is the opposite of a "runtime error".