Search code examples
cstatic-analysislexical-analysis

How can I get all modulo(%) operation in my C source code


How can I get all modulo(%) operation in my c source code? I don't think a regular expression can do it, due to C MACRO inclusion. And, must take care of string printf formatting.

Which static analyse source code can I use to do this? For exemple, Codesonar or codecheck "only" try find problems, not that.

I want to check manually all modulo operation with zero. (like division by 0).


Solution

  • It's probably not the best way to do this, but it seems to work. Here's my test file:

    #include <stdio.h>
    
    #define MACRO %
    
    int main(void) {
        int a = 1%1;
        int b = 1 MACRO 1;
        printf("%1s", "hello");
    }
    

    Then I ran this and got some useful output:

    $ clang -fsyntax-only -Xclang -dump-tokens main.c 2>&1 > /dev/null | grep percent
    percent '%'     Loc=<main.c:6:14>
    percent '%'  [LeadingSpace] Loc=<main.c:7:15 <Spelling=main.c:3:15>>
    

    Short explanation:

    This is the output from the lexical analysis. The command seem to write to stderr instead of stdout. That's the reason for 2>&1 > /dev/null. After that I'm just using grep to find all occurrences of the modulo operator.