NO

Author Topic: snprintf broken?  (Read 4292 times)

akko

  • Guest
snprintf broken?
« on: May 14, 2007, 10:36:58 PM »
/* 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

  • Guest
Re: snprintf broken?
« Reply #1 on: May 14, 2007, 10:58:43 PM »
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
« Last Edit: May 15, 2007, 08:08:54 AM by JohnF »

akko

  • Guest
Re: snprintf broken?
« Reply #2 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.

JohnF

  • Guest
Re: snprintf broken?
« Reply #3 on: May 15, 2007, 05:57:33 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

Offline Pelle

  • Administrator
  • Member
  • *****
  • Posts: 2266
    • http://www.smorgasbordet.com
Re: snprintf broken?
« Reply #4 on: June 05, 2007, 09:20:30 AM »
It appears the snprintf code is correct, and the help file is not. Probably cut & paste error.
/Pelle