MCJack123 / craftos2

A fast, modern, and feature-filled ComputerCraft emulator written in C++.
https://www.craftos-pc.cc
Other
217 stars 25 forks source link

`string.rep` causes "fake" memory leak #328

Closed Possseidon closed 9 months ago

Possseidon commented 10 months ago

Describe the bug

Whenever string.rep is called it causes a small "fake" memory leak. What I mean by "fake" is, the process doesn't actually leak memory, but Lua thinks it does. In other words, collectgarbage("count") and gcinfo() return wrong results.

I've only tested string.rep so far, but there's a decent chance other functions might be affected as well. I think there's a good chance it's not actually an issue with string.rep itself but instead with how memory usage is tracked altogether.

To Reproduce

Open the built-in lua interpreter and run the following snippet:

old = collectgarbage("count") for i = 1, 1000000 do (" "):rep(1000) end print(collectgarbage("count") - old)

This runs a whole lot of calls to string.rep without storing the resulting string anywhere so they can be gc'ed pretty much immediately and then prints the difference in total used memory in KB.

Expected behavior

After running the snippet above I'd expect collectgarbage("count") and gcinfo() to return close to zero bytes, and yet they return almost a full GB for me, although the exact value varies. (And yes, if you execute it multiple times and look at the old variable, the actual result does increase GB by GB as well.) When inspecting the process itself (using the Windows Taskmanager in my case) it shows that it stays at ~8MB the entire time, so there is no actual memory leak.

Environment