Question

My software validation group is testing a piece of code like the following:

unsigned int alarm_id;  
char         alarm_text[16];  
static const char text_string[] = "105, Water_Boiling";  
signed int   arguments_satisfied =  
    sscanf(text_string,  
           "%3d, %16s",
           &alarm_id, &alarm_text[0]);
if (arguments_satisfied < 2)
{
   system_failure();
}

Using the code fragment above, is there a way to get sscanf to return a value greater than 2 without changing the format specifier or changing the arguments to sscanf?

They are exercising the if statement expression, using a unit testing tool.

For C++, are there any differences with the above fragment when compiling as C++?
(We plan to use the same code, but compile as C++.)

FYI, we are using an ARM7 processor with IAR Embedded Workbench.

Was it helpful?

Solution

sscanf returns the number of arguments converted. It cannot convert more arguments than you have told it about. Therefore, unless the format string is changed, sscanf cannot return a value greater than 2. One possible exception -- it may be possible for EOF to be returned if you run out of data before the first argument is converted, but I suspect that only applies to scanf, not sscanf.

OTHER TIPS

For many toolchains (and I'm pretty sure IAR is one), if you have a symbol in an object file and a library, the linker will link to the one in an object file in preference to the one in the library.

So you may be able to provide your own sscanf() function to link during tests and have it return whatever you like.

If the linker has a problem with a symbol conflict between your sscanf() implementation and one in the library, and alternative that may work is to have you unit test sscanf() use a different name (such as unittest_sscanf) and have the build system define a macro to rename sscanf() during the build using something like /Dsscanf=unittest_sscanf for the module under test.

Of course, it may be tricky to make sure that other sscanf() calls that aren't under test don't cause problems.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top