This is the mail archive of the libc-alpha@cygnus.com mailing list for the glibc project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

snprintf and sprintf act differenting when writing to an argument


>Submitter-Id:	net
>Originator:	Andy Bakun
>Confidential:	no
>Synopsis:	sprintf and snprintf don't operate the same when a source string is also the destination string
>Severity:	non-critical
>Priority:	low 
>Category:	libc
>Class:		sw-bug
>Release:	libc-2.0.111
>Environment:   Linux RedHat 5.1/5.2
Host type: i386-redhat-linux-gnu
System: Linux jupiter.reac.com 2.0.35 #2 Tue Oct 20 19:46:21 CDT 1998 i686 unknown
Architecture: i686

Addons: crypt glibc-compat linuxthreads

Build CC: egcs
Compiler version: egcs-2.90.27 980315 (egcs-1.0.2 release)
Kernel headers: UTS_RELEASE
Symbol versioning: yes
Build static: yes
Build shared: yes
Build pic-default: no
Build profile: yes
Build omitfp: no
Build bounded: no
Build static-nss: no
Stdio: libio

>Description:
  The results of sprintf and snprintf are not the same when passing a source string argument that is also 
  the destiniation string.  Specificly, when the destination string argument is also specified as a source 
  string, sprintf allows this, and snprintf clears the destiniation string first.

>How-To-Repeat:
  The code

    char x[128];
    sprintf(x, "one two");
    sprintf(x, "%s three four", x);
    printf("%s\n", x);

  outputs
  one two three four

    char x[128];
    snprintf(x, 128, "one two");
    snprintf(x, 128, "%s three four", x);
    printf("%s\n", x);

  outputs
   three four

>Fix:
  Workaround:
    Copy the source string to a temporary area or use a series of str[n]cats.
  Fix:
    Document in the man page this difference, or make them both operate the same.  _I_ personally think that
      snprintf(x, y, "%s", x)
    should be allowed and NOT erase x before copying, especially if x would end up at the start of the start
    of the destination array, but if whoever fixes this feels like sprintf should operating like snprintf here,
    then so be it.  I am not familar with what the ANSI standard says about this.




Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]