News:

Download Pelles C here: http://www.smorgasbordet.com/pellesc/

Main Menu

snprintf broken?

Started by akko, May 14, 2007, 10:36:58 PM

Previous topic - Next topic

akko

/* 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);
}

JohnF

#1
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

akko

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.

JohnF

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

Pelle

It appears the snprintf code is correct, and the help file is not. Probably cut & paste error.
/Pelle