Re: Is this a valid use lua_pushexternalstring()
Błażej Roszkowski <[email protected]>
| Newsgroups | gmane.comp.lang.lua.general |
|---|---|
| Message-ID | <CAOc0etGHf41PZe2BWx+ScK1HjORt03ti3GOx6VHL1TeYibRtNA@mail.gmail.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. On Tue, 3 Feb 2026 at 16:15, Marc Balmer <[email protected]> wrote: > 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); > > > > -- > 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 [email protected]. > To view this discussion visit > https://groups.google.com/d/msgid/lua-l/FCDAFABE-065F-4209-A339-C9BC149B259C%40gmail.com > . > -- 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 [email protected]. To view this discussion visit https://groups.google.com/d/msgid/lua-l/CAOc0etGHf41PZe2BWx%2BScK1HjORt03ti3GOx6VHL1TeYibRtNA%40mail.gmail.com.