0

Imagine there is a code like:

#include "stdio.h"
int divide(int a, int b, float *res)
{
        if (b == 0)
                return 0;
        *res = (float)a/b;
        return 1;
}

int main()
{
        float res;
        divide(2,5,&res);
        printf("%f", res);
        return 0;
}

The obvious mistake here is that the return of divide() is not being checked before printing the result. Is there a way to detect such error automatically? (like script, tool or service) It would be very useful for a large codebase. I have not found any gcc or clang flags that could help. cppcheck also seems not to offer such feature.

y_159
  • 458
  • 3
  • 15
Draif Kroneg
  • 743
  • 13
  • 34
  • Also `[[nodiscard]]` for C++ code bases, but I suppose this question is pure C? – Ext3h Aug 11 '21 at 05:47
  • Regarding `cppcheck`: We use MPLAB X IDE which comes with cppcheck to do MISRA checks. There I get a MISRA finding when I don't use (or cast to `void`) the return value of `memcpy` etc. Therefore I would expect cppcheck to be able to warn you. – Gerhardh Aug 11 '21 at 09:29
  • There's an attribute in GCC called `warn_unused_result attribute`. You might want to use that. Add a macro definition at the top of your .c file. `#define WARN_UNUSED __attribute__((warn_unused_result))` – phramos07 Aug 19 '21 at 17:33

0 Answers0