04-05-2014 03:19 AM - edited 04-05-2014 03:20 AM
using cvi 2013 edition, OS is 64-bit windows 7. when using the call :
sprintf ( varStr, "%s, %s, %s", text_1, text_2, num);
here, the parameter "num" is an integer, and the conversion sign should be : %d. when compilling the program, the compiler cannot recognize the error. I think this shoud be treated before running.
David
04-05-2014 02:28 PM
Same reason as you are not warned by the compiler when you type:
printf ("Hello Woldr");
The contents of the format string is evaluated at runtime, not compile time.
Compiler checks for type consistency and it is satisfied in that function call.
If you look at the prototype of sprintf, you would see smth like:
int sprintf(char *str, const char *format, ...)
It uses a variable argument list, which also requires the inputs after the format string can only be extracted and evaluated during run time.
04-05-2014 08:01 PM - edited 04-05-2014 08:03 PM
But once fogetting input the parameter "num" , the compilier should know that there is a parameter missed. This should be checked at the compiling time.
04-05-2014 11:03 PM
Well, to achieve that, the compiler has to count the format specifiers in the format string.
This is also not possible, or better to say, not the concern of the compiler.
The "..." at the end of the function input list is the variable part.
You can put as many inputs as you like in there as long as they fit into the stack size reserved for the application.
You are right, if you think it is too much of a risk for the health of the programs.
But it is also a very powerful feature. Similar to the concept of raw pointer operations.
You can crash a computer by a few lines of "irresponsibly" written pointer code.
It is a gift, and a curse 🙂
04-07-2014 01:37 AM - edited 04-07-2014 01:38 AM
Hello all,
Enabling the Format warning (-wformat) for the active configuration will yield a compiler warning on that statement:
warning: conversion specifies type 'char *' but the argument has type 'int' [-Wformat]
Best regards,
= Nelu F. || National Instruments.
04-07-2014 05:06 AM
Hi Nelu,
That really surprised me!
So it is actually possible to check the type consistency for printf family of functions, is that right?!
So I hope it is a new feature?
I should have heard or read about it otherwise ...
04-07-2014 05:23 AM
Hello ebalci,
You are correct. Starting with LabWindows/CVI 2013, the compiler can check the type consistency for printf family of functions. It currently returns a warning with the flag -wformat. This warning can be enabled individually from the Compiler Warnings dialog (under Warning Level All).
Best regards,
= Nelu F. || National Instruments.
04-07-2014 08:00 PM
Hi All,
Is this the config: the "Format" checkbox?
04-08-2014 02:03 AM
Hello David_Lee,
Yes, that is the warning. Did it work for you?
Best regards,
= Nelu F. || National Instruments.
04-08-2014 10:28 PM
Yes, it is working. Thanks a lot!