Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

snprintf negative/zero value of buffer size

Tags:

c

printf

buffer

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, ...);
like image 844
Sumit Trehan Avatar asked Dec 02 '22 14:12

Sumit Trehan


1 Answers

Quoting C11, chpater §7.21.6.5, The snprintf() function

int snprintf(char * restrict s, size_t n,const char * restrict format, ...);

[...] If n is zero, nothing is written, and s may 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;

like image 116
Sourav Ghosh Avatar answered Dec 20 '22 08:12

Sourav Ghosh