Monday, June 14, 2010

C programming: the "size" argument and return value of snprintf()


Considering the following code. What would the string "s" and the return value "r" be?

   char s[10];
   int r = snprintf(s, 3, "%d", 12345);

It turns out that s would become "12" and r would be 5. Why?

The second argument "size" of snprintf(char *str, size_t size, const char *format, ...) allows only up to 3 characters to be written into s. And these 3 characters includes the null terminator '\0'.

The output has to be truncated to be put into s. When the output is truncated, the return value of snprintf() would be set to the number of characters should have been written -- excluding the trailing '\0'.

To check whether a string is truncated, we should compare the return value with the second argument "size". And remember, the "size" argument includes trailing '\0', but the return value excludes it. This sounds weird, but it is how it works.

No comments:

 
Get This <