Is this a valid use lua_pushexternalstring()

18 views
Skip to first unread message

Marc Balmer

unread,
Feb 3, 2026, 10:15:01 AM (16 hours ago) Feb 3
to lu...@googlegroups.com
The following code „seems“ to work, but is it valid to simply pass free() as allocf?

char *mystring;

mystring = strdup(„just an example“);

lua_pushexternalstring(L, mystring, strlen(mystring), (lua_Alloc)free, mystring);



Błażej Roszkowski

unread,
Feb 3, 2026, 10:59:13 AM (15 hours ago) Feb 3
to lu...@googlegroups.com
No, it's technically undefined behavior and you should not do that.

It happens to work because in case of integers or pointers the arguments and
result are passed via registers on most calling conventions on most platforms
you will run into.

In your case Lua's compiled C code will set 4 registers for ud, ptr, osize and
nsize, jump to your function (free) and that function will only read the
ud register (that you made contain the string too) so it's "okay". It will
also not set the return register so it will contain some random temporary
garbage when free returns to Lua. Luckily Lua doesn't check it.

If Lua checked that your dellocation function returns NULL, or if your
deallocation function was using a different calling convention (one that
uses different registers or uses or trashes the stack) your code
wouldn't work anymore.

You also throw away type safety with that cast, so if Lua changed its alloc
function to e.g. take extra argument lua_State as the first argument in a
future release, your code would still compile, but then crash at runtime,
instead of giving you a clear compile error about argument list mismatch.

--
You received this message because you are subscribed to the Google Groups "lua-l" group.
To unsubscribe from this group and stop receiving emails from it, send an email to lua-l+un...@googlegroups.com.
To view this discussion visit https://groups.google.com/d/msgid/lua-l/FCDAFABE-065F-4209-A339-C9BC149B259C%40gmail.com.
Reply all
Reply to author
Forward
0 new messages