From: Justin C. <mi...@ce...> - 2007-07-12 23:09:24
|
On 12 Jul 2007 at 23:18, Fabio Napoleoni wrote: > First of all, hi to everyone because this is my first message. > > I think that I've found a bug, or maybe I'just think wrong. Before I > sumbit a bug report i ask in this list. > > Here is the code: > > #include <stdio.h> > #include <string.h> > > #define BIG_STRING "qwertyuiopqwertyuiopqwertyuiopqwertyuiopqwertyuiop" > > int main() { > char buf[12]; > int written; > written =3D snprintf(buf, sizeof(buf), "%s", BIG_STRING); > printf("Content is: %s\nlength is %d\nwritten is %d\n", buf, > strlen(buf), written); > return 0; > } > > and here is the result: > > Content is: qwertyuiopqw=BF " > length is 15 > written is -1 > > Now from man snprintf I read: > > "The snprintf() and vsnprintf() functions will write at most size-1 of > the characters printed into the output string (the size'th character > then gets the terminating `\0'); if the return value is greater than > or equal to the size argument, the string was too short and some > of the printed characters were discarded. The output is always > null-terminated." > > Therefore the correct output should be: > > Content is: qwertyuiopq > length is 11 > written is -1 > > I've tried this code on my Asus Notebook with WindowsXP and the last, > just updated, mingw version. The result is the same on another PC with > Win2k and an older version of Mingw. > > Can anyone could explain me what's wrong? > > -- > Fabio Napoleoni > f.n...@gm... > I think the main "bug" is in your programme, not in mingw or the implementation of snprintf (which is presumably the Microsoft _snprintf, because mingw does not provide its own C run-time library implementation). According to the ISO C99 standard (clause 7.19.6.5), the output of snprintf is not always null-terminated. It is only null-terminated if the= 2nd argument is less than the length that the output string would have if it were not truncated. Thus, your programme has a bug, in the sense that you use printf with "%s" to output a string which is not null-terminated. You get garbage characters beyond the 12 which were stored in the buffer. This is precisely what you should expect to happen when the implementation of snprintf is standard-confirming. What is not standard-conforming is the return value of -1. Acclording to the the standard, the return value of snprintf should be length the output string would have if it were not truncated (in this case 50). This is not really a bug, but merely a non-conformance issue. The Microsoft C run-time library, which mingw uses, is not, and does not claim to be, standard-conforming. Hope that clarifies things. Justin |