PORTING.MACRO.NUMTYPE

Macro describing a builtin numeric type

The PORTING checkers identify code that might rely on specific implementation details in different compilers. The PORTING.MACRO.NUMTYPE checker detects situations in which a macro describing a built-in numeric type is used.

Vulnerability and risk

It is typical for compilers to provide "courtesy" numeric limits (normally in limits.h) for their particular data model and capabilities. Using these values across platforms is dangerous, as the limits provided by another compiler can be different, and of entirely different widths (in terms of bit-wise representation). This practice can cause stack overflow, numeric overflow or underflow, operational runtime budget exhaustion, and many other problems.

Mitigation and prevention

Define your own limits so you know exactly what you're dealing with, rather than relying on an abstract number provided by the compiler on a particular platform.

Vulnerable code example

Copy
   extern void do_something_that_takes_a_while();
   void foo()
   {
      for( int i = 0; i < INT_MAX; i++ )
        do_something_that_takes_a_while();
   }

In moving this code between two platforms (such as 16-bit and 32-bit), the operational budget for this function can expand exponentially.

Fixed code example

Copy
   #define MAX_OPS 65535
   extern void do_something_that_takes_a_while();
   void foo()
   {
      for( int i = 0; i < MAX_OPS; i++ )
        do_something_that_takes_a_while();
   }

This code defines its own limit, ensuring that the same numeric value is used regardless of any move between platforms.