nodemcu-firmware: The LGC usage count is incorrectly calculated if luaM_free() is used to free arrays in our modules

Expected behavior

Read line, no permanent memory consumption.

Actual behavior

Readline works, but causes permanent memory consumption.

Console output directly after startup:

=collectgarbage(“count”) 4

Function is run via console:

increment_job_counter()

Memory usage increases:

=collectgarbage(“count”) 5

increment_job_counter() =collectgarbage(“count”) 6

increment_job_counter() =collectgarbage(“count”) 7

collectgarbage() =collectgarbage(“count”) 7

This example can be continued until memory overflow error occurrs.

Test code

This is my minimalistic init.lua

function increment_job_counter()
	if file.exists("job.counter") == true then
		local handle = file.open("job.counter", "r")
		local val = tonumber(file.readline()) + 1
		handle = file.open("job.counter", "w+")
		handle:writeline(tostring(val))
		handle:close()
		handle = nil
		val = nil
	else
		local handle = file.open("job.counter", "w+")
		handle:writeline(tostring(1))
		handle:close()
		handle = nil
	end
end

NodeMCU version

branch: master (latest) commit: 67027c0d05f7e8d1b97104e05a3715f6ebc8d07f

Hardware

Wemos D1 mini pro

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Comments: 19 (4 by maintainers)

Most upvoted comments

Sorry I should have been clearer as to what I meant - I wasn’t objecting to leveraging Lua’s memory management functions, I totally get what benefits they provide. My issue is that luaM_free() looks like it can correctly free any pointer returned by luaM_malloc() regardless of type (because that’s how malloc() and free() behave) - but it can’t, and pretty much every use of it I can find in nodemcu assumes that it can. For untyped char* pointers one must call luaM_freemem() also passing in the size of the original allocation. My musings therefore were towards should there be some sort of wrapper around luaM_malloc()/luaM_free[mem]() which make it less likely people will make the mistake of thinking those functions work like malloc and free.

Edit: grammar, clarification.