Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printf, wprintf, %s, %S, %ls, char* and wchar*: Errors not announced by a compiler warning?

Tags:

c

mingw

I have tried the following code:

wprintf(L"1 %s\n","some string"); //Good wprintf(L"2 %s\n",L"some string"); //Not good -> print only first character of the string printf("3 %s\n","some string"); //Good //printf("4 %s\n",L"some string"); //Doesn't compile printf("\n"); wprintf(L"1 %S\n","some string"); //Not good -> print some funny stuff wprintf(L"2 %S\n",L"some string"); //Good //printf("3 %S\n","some string"); //Doesn't compile printf("4 %S\n",L"some string");  //Good 

And I get the following output:

1 some string 2 s 3 some string  1 g1 %s  2 some string 4 some string 

So: it seems that both wprintf and printf are able to print correctly both a char* and a wchar*, but only if the exact specifier is used. If the wrong specifier is used, you might not get a compiling error (nor warning!) and end up with wrong behavior. Do you experience the same behaviour?

Note: This was tested under Windows, compiled with MinGW and g++ 4.7.2 (I will check gcc later)

Edit: I also tried %ls (result is in the comments)

printf("\n"); wprintf(L"1 %ls\n","some string"); //Not good -> print funny stuff wprintf(L"2 %ls\n",L"some string"); //Good // printf("3 %ls\n","some string"); //Doesn't compile printf("4 %ls\n",L"some string");  //Good 
like image 830
Antonio Avatar asked Jul 17 '13 13:07

Antonio


1 Answers

I suspect GCC (mingw) has custom code to disable the checks for the wide printf functions on Windows. This is because Microsoft's own implementation (MSVCRT) is badly wrong and has %s and %ls backwards for the wide printf functions; since GCC can't be sure whether you will be linking with MS's broken implementation or some corrected one, the least-obtrusive thing it can do is just shut off the warning.

like image 97
R.. GitHub STOP HELPING ICE Avatar answered Oct 03 '22 02:10

R.. GitHub STOP HELPING ICE