/* Test snprintf */
#include <stdlib.h>
#include <stdio.h>
char buf[7]="xxxxxx";
int main() /* PellesC 4.50.113 prints 1234 ??? */
{
snprintf(buf,5,"%d",12345);
printf("\nYou should see 12345x : %s\n",buf);
return(0);
}
1234 plus the null termination is 5 chars.
edit:
The C99 spec explains it.
==========================
int snprintf(char * restrict s, size_t n, const char * restrict format, ...);
Description
2 The snprintf function is equivalent to fprintf, except that the output is written into an array (specified by argument s) rather than to a stream. If n is zero, nothing is written, and s may be a null pointer. Otherwise, output characters beyond the n-1st are discarded rather than being written to the array, and a null character is written at the end of the characters actually written into the array. If copying takes place between objects that overlap, the behavior is undefined.
==========================
John
Thanks for pointing this out. It seems I fell into an old snprintf pitfall:
http://lwn.net/Articles/69419/
I was porting code that works under gcc, and never suspected that such a simple thing could cause a problem with gcc, which is the most widely used C compiler in the world.
Quote from: akko on May 15, 2007, 02:36:36 PM
Thanks for pointing this out. It seems I fell into an old snprintf pitfall:
http://lwn.net/Articles/69419/
I was porting code that works under gcc, and never suspected that such a simple thing could cause a problem with gcc, which is the most widely used C compiler in the world.
C99 changed snprintf.
I notice however that the PellesC help file says that snprintf
==================
Returns:
Number of written characters, not counting the terminating null character ('\0').
==================
This is not correct: this is what the C99 standard says.
The snprintf function returns the number of characters that would have been written had n been sufficiently large, not counting the terminating null character
==================
Which seems crazy anyway.
John
It appears the snprintf code is correct, and the help file is not. Probably cut & paste error.