So I've got a compiler bug with their low level _fconvert() function that the vendor has marked as low priority, but the effect is that the embedded system will crash if I send a NaN value to a printf() style function. I'd like to write a wrapper for sprintf() that parses for floats, and if they are NaN values, they get replaced by a macro value. I think I get the basics on how to pass the variable parameter list, but not how to parse/replace. Can anyone help me on this?
int no_nan_sprintf(char *target_str, const char *format, ...)
{
va_list args;
va_start(args, format);
//need help here, something like
int idx;
for (idx = 0; idx < sizeof(args); idx++)
{
if (isnan(args[idx]))
{
args[idx] = NAN_SUBSTITUTE_VALUE;
}
}
//this should be tha call I want to make to sprintf
sprintf(target_str, format, args);
va_end(args);
} /* no_nan_sprintf */
The nain problem filtering the entire call to
*printf
would have is that it's not enough to blindly replace all arguments - you need to be able to do this only for floating point parameters.That means you'll need to intelligently process the format string itself to ensure you don't modify pointers or integers.
In terms of just ensuring not passing NaNs, I'd opt for changing something like:
with:
That way, you don't have to worry about re-implementing all the hard details of the
printf
family, just filter the specific variables causing trouble. Thefx
function can be made as complex as needed such as using a macro instead of zero, allowing a default to be provided per-call and so on.Obviously this will only work if you can change all the calls where NaN is being passed. If they're buried deep within code you don't control, you may well have to go the more difficult route of replacing entire chunks of the standard library.