Re: Is this a valid use lua_pushexternalstring()
Marc Balmer <[email protected]>
| Newsgroups | gmane.comp.lang.lua.general |
|---|---|
| Message-ID | <[email protected]> |
> Am 03.02.2026 um 16:58 schrieb Błażej Roszkowski <[email protected]>: > > 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. Thank you for your comprehensive answer, which makes sense and was what I already suspected. I now use this function to free external strings: static void * free_external_string(void *ud, void *ptr, size_t osize, size_t nsize) { free(ud); return NULL; } And call lua_pushexternalstring() like so: lua_pushexternalstring(L, d->data, d->len, free_external_string, d->data); - Marc -- 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/353F128C-83CF-4597-B81F-058BF1240C8A%40gmail.com.