ludocode / mpack

MPack - A C encoder/decoder for the MessagePack serialization format / msgpack.org[C]
MIT License
521 stars 82 forks source link

Allow NULL buffers with 0 length to be used #97

Closed schmidtw closed 2 years ago

schmidtw commented 2 years ago

Buffers and strings that are 0 length may be NULL and that is ok. Instead of asserting and exiting, they should be output as zero length versions of the encoded types. This also applies for the cstr strings.

This is in response to issue #96 .

ludocode commented 2 years ago

If count is 0 then you're correct the pointer should never be dereferenced. It should definitely allowed to be NULL. I'm not sure why these asserts didn't allow zero count; I'm not sure if I used to believe otherwise and changed my mind or if it's just an oversight. Either way thanks for fixing it.

As for allowing NULL for cstr, I'm less comfortable with that. strlen(NULL) is an error after all. GCC warns against it under -Wall and it segfaults under at least glibc, and probably most other platforms. I don't think we should allow it for our own null-terminated functions. A null-terminated string must at least point to a null-terminator.

I think using NULL as a valid string used to only work decades ago for historical reasons. As I understand it early machines would put a zero byte at physical address zero so that a NULL pointer could double as an empty string. Dereferencing it would yield a null terminator so early string functions didn't have to check for NULL. This hack stopped working with the advent of memory protection; compilers had to make empty strings point to a real zero byte mapped somewhere in the process space to avoid systems having to add NULL checks to all their old string functions. This convention still holds today: no C string function checks for NULL and callers can never pass in NULL.

I took the liberty of reverting some of the changes in your PR and keeping the rest. I hope that's OK. Thanks for the fix!

schmidtw commented 2 years ago

Great write up & I appreciate your point of view. Thank you for making the adjustments as well.