If a negative number or 0 is passed as the second argument to snprintf(), will it write at the provided buffer position. Want to have the views that this should not result in any unexpected behavior.
int snprintf(char *str, size_t size, const char *format, ...);
Quoting C11, chpater §7.21.6.5, The snprintf() function
int snprintf(char * restrict s, size_t n,const char * restrict format, ...);[...] If
nis zero, nothing is written, andsmay be a null pointer.
So, in case you pass 0, nothing is written.
In case if you pass a -ve value, it may create issues, as the second argument, is of type size_t which is unsigned. So, the signed value will be treated as unsigned producing a unwanted size. This may cause issues (memory overrun) as the size is likely to be more than the supplied buffer can handle, which invokes undefined behavior.
. Nevertheless, as long as the buffer is large enough to be able to hold the supplied data, the supplied data will be written to the buffer.
From §7.19, <stddef.h>
size_t
which is the unsigned integer type of the result of the sizeof operator;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With