2 ms·
Nice work. I always have understood that snprintf does not write a null character when the produced string is longer than the given size. The snprintf function
by fjfaase 1y ago
Nice work. I always have understood that snprintf does not write a null character when the produced string is longer than the given size. The snprintf function also can be called with a null pointer to calculate the length of the produced string.
You could add a c file with some unittests.
- Forgret 1y agoThanks, I will make and add unit tests As you requested, I'm already starting to do it, but in the meantime, if you want, you can support the project with a star. :)
- wahern 1y ago> I always have understood that snprintf does not write a null character when the produced string is longer than the given size. snprintf always null-terminates when the buffer length is greater than 0 and there's no error. That is, if snprintf returns >= 0 and the buffer length is > 0, the output is null-terminated. This should be clear from your local snprintf(3) man page (e.g. https://man.openbsd.org/snprintf https://man.openbsd.org/snprintf), but also see the C23 standard (https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3220.pdf https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3220.pdf) and POSIX (https://pubs.opengroup.org/onlinepubs/9799919799/ https://pubs.opengroup.org/onlinepubs/9799919799/).
- fjfaase 1y agoYou are right. I verified this myself. I do not know where I got this wrong. Maybe this was different in earlier implementations.
- wahern 1y agoIt was first added to the Single UNIX Specification (SUS) in 1997. Perhaps there was some oddball non-conformant implementation at the time, but in those cases the standard would usually use a different name. There's the infamous strncpy, of course, which understandably could cause some confusion. And various non-vendor faux-snprintf implementations, like uprintf, that have different semantics. It's hazardous to reuse a standardized name like snprintf, even as a suffix, in an API but not implement the same fundamental semantics.
- fjfaase 1y agoI got this wrong from Microsoft Visual Studio (before 2015 and Windows 10) where the function snprintf did not add the null character. The function _snprintf still has the behavior that it does not add the null character. See section 'Remark' on: https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/snprintf-snprintf-snprintf-l-snwprintf-snwprintf-l?view=msvc-170 https://learn.microsoft.com/en-us/cpp/c-runtime-library/refe...