crystal-lang / crystal

The Crystal Programming Language
https://crystal-lang.org
Apache License 2.0
19.26k stars 1.61k forks source link

Invalid memory error accessing local variable from closure when closure is stored in an array #14581

Closed aramvisser closed 2 months ago

aramvisser commented 2 months ago

I encountered an "Invalid memory access" error in my project when accessing a local variable inside a closure. I was able to reduce the error the the following example:

struct Foo
  getter values = {1, 2, 3, 4}
end

foo = Foo.new

procs = [] of ->
procs.push -> { foo }

procs.first.call # Calling the proc gives the error

https://play.crystal-lang.org/#/r/gtgl

Running that gives an "Invalid memory access" error:

Invalid memory access (signal 11) at address 0x0
[0x5653d17eaac6] *Exception::CallStack::print_backtrace:Nil +118 in /home/crystal/.cache/crystal/crystal-run-eval.tmp
[0x5653d17d9586] ~procProc(Int32, Pointer(LibC::SiginfoT), Pointer(Void), Nil) +310 in /home/crystal/.cache/crystal/crystal-run-eval.tmp
[0x7f241f2ab770] ?? +139793118443376 in /usr/lib/libc.so.6
[0x5653d17da126] ~procProc(Foo) +6 in /home/crystal/.cache/crystal/crystal-run-eval.tmp
[0x5653d17c9b2f] __crystal_main +1263 in /home/crystal/.cache/crystal/crystal-run-eval.tmp
[0x5653d188e316] *Crystal::main_user_code<Int32, Pointer(Pointer(UInt8))>:Nil +6 in /home/crystal/.cache/crystal/crystal-run-eval.tmp
[0x5653d188e28a] *Crystal::main<Int32, Pointer(Pointer(UInt8))>:Int32 +58 in /home/crystal/.cache/crystal/crystal-run-eval.tmp
[0x5653d17d7036] main +6 in /home/crystal/.cache/crystal/crystal-run-eval.tmp
[0x7f241f294cd0] ?? +139793118350544 in /usr/lib/libc.so.6
[0x7f241f294d8a] __libc_start_main +138 in /usr/lib/libc.so.6
[0x5653d17c9565] _start +37 in /home/crystal/.cache/crystal/crystal-run-eval.tmp
[0x0] ???

I assume this has to do with foo not being available anymore from inside the closure.

But this error only seems to happen under specific circumstances. Making any of the following (seemingly unrelated) changes to the codes fixes the error.

I was able to eventually fix the error in my project by making some of these small changes. But this error should not happen in the first place, since as far as I can tell the code is valid.

HertzDevil commented 2 months ago

Duplicate of #10911?

straight-shoota commented 2 months ago

Seems like it. Let's continue tracking this over there.

Duplicate of #10911