ransh
ransh

Reputation: 1712

Alternative to printf with limited number of arguments?

Misra 2004 has the following rule:

Rule 16.1: Functions shall not be defined with variable numbers of arguments

Therefore, functions like printf can't be used with rule 16.1.

uint32_t debug_print(char *format, ...)
{
   int int_ret_val=0;

   uint32_t ret_val = ERR_NO_ERROR;
   va_list arguments;
   va_start(arguments, format);

   ret_val = vprintf(format, arguments);

   va_end(arguments);

   return ret_val;
}

I've searched for alternative but did not find any.

Is it that all family of c commands for logging a string formatted message ("%d,%f,..") use variable list ?

Upvotes: 3

Views: 1391

Answers (2)

Andrew
Andrew

Reputation: 2322

Strictly speaking MISRA-C:2004 Rule 16.1 (now MISRA C:2012 Rule 17.1) does not apply to the Standard Library functions, but only to User-defined functions using stdarg.h

However MISRA-C:2004 Rule 20.9 (now MISRA C:2012 Rule 21.6) precludes the use of the Standard Library input/output functions (in production code) - which explicitly "bans" the use of printf() and its related functions

If you really need to use either stdarg.h or stdio.h then a Deviation is the appropriate route to follow.

Upvotes: 0

Lundin
Lundin

Reputation: 214495

Indeed this bans the use of printf. In fact MISRA bans the whole of stdio.h from production code. The reason is simply that these are some of the most horribly unsafe functions ever designed for any programming language. They have non-existent type safety and multiple security/safety problems.

This is also true for all variadic functions, even though the stdio.h ones are particularly bad because of their complexity and their love for invoking numerous forms of undefined behavior. In addition, variadic functions come with the dangerous "default argument promotion" rule.

So forget all about these functions in mission-critical systems.

  • On a hosted system (OS), use system-specific API:s instead.
  • On a freestanding system (no OS), stdio doesn't make much sense to begin with and you should use whatever custom interface that makes sense for the application.

Upvotes: 7

Related Questions