lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]




> On 2 Apr 2023, at 15:37, Luiz Henrique de Figueiredo <lhf@tecgraf.puc-rio.br> wrote:
> 
> 
>> 
>> This question was also asked in Stack Overflow:
>> https://stackoverflow.com/questions/75786344/lua-requests-free-on-null-ptr-regularly
> 
> The OP is asking why Lua should ever try to free a NULL pointer.
> The question is not about what C does in this case.

Purely for simplicity. The description states that a size of zero should behave as if free() was called on the pointer, assuming that the pointer was allocated with malloc(), calloc() or realloc() and then should return NULL.

It’s absolutely valid to do an explicit NULL pointer check inside that condition for nsize == 0 and skip the call to free() or whatever is the equivalent for your memory manager, but in the case of free() it is usually not done and even considered bad style since free() itself is guaranteed to do that (if it is standard C compliant).

But your embedded system memory manager might have other function names and not like to have its deallocate() function being called with a NULL pointer, so your mileage may vary.

The main thing here is that you don’t HAVE to call free() on a NULL pointer here but you CAN since free() is guaranteed to do nothing with that invalid pointer. And it saves an extra NULL pointer check in your code.

Rolf Kalbermatter