delorie.com/djgpp/bugs/show.cgi   search  
Bug 000293

When Created: 07/08/1999 03:00:02
Against DJGPP version: 2.02
By whom: anarko@flashback.net
Abstract: sprintf bug ? short code example included
/*
 Is this a bug in gcc or djgpp or did i only drank to much coffe?

 Description: Tries to copy the string 'test' into the
  variable 'testvar', sprintf() returns that 4 bytes was
  successfully written, but when i trys to display the
  string it says it's empty.

 Output from program below:
 --------------------------
 Wrote 4 bytes
 String now is (null)

 Compiled with gcc foo.c -o foo.exe -Wall
*/


#include <stdio.h>
#include <string.h>

int main()
{
    unsigned char   *testvar;


    printf("Wrote %d bytes\n", sprintf(testvar,"test") );
    printf("String now is %s\n",testvar);

    return 0;
}

Note added: 07/09/1999 11:00:20
By whom: broeker@physik.rwth-aachen.de
The bug is in the example code, not in DJGPP: 'testvar' is not initialized
to any writable storage. Doing anything through a wild pointer (including
trying to sprintf() to it) causes undefined behaviour, by definition of
the C standard. On my Linux box here, e.g., the example program gave
a segfault, instead.

BTW: test compilations should be done with '-Wall -O', not just '-Wall'.
See the description of '-Wuninitialized' in 'info gcc', for the reason.
Adding '-W' and/or '-ansi -pedantic' to the command line may also be
useful.

Closed on 07/09/1999 11:00:02: Error in example program, not in DJGPP
By whom: broeker@physik.rwth-aachen.de



  webmaster     delorie software   privacy  
  Copyright 2010   by DJ Delorie     Updated Jul 2010