Menu

Custom assert macro

Jon Read
2017-03-02
2017-03-07
  • Jon Read

    Jon Read - 2017-03-02

    Hi,

    Is it possible to handle a custom assert-style macro?

    In our code these asserts cause a system reboot when an invalid state is detected, and hence execution never proceeds past the macro if the expression evaluates to false.

    For that reason cppcheck will often warn about accesses out of bounds, eg:

       _ASSERT(RESOURCE_MAX_COUNT > resource_num);
       _ASSERT(m_resource_info[resource_num].valid); 
    

    The second ASSERT macro here gives a warning, even though execution will have stopped at the line before if resource_num is out of range.

    Thanks!
    Jon

     
  • Daniel Marjamäki

    How is your ASSERT macro defined? If the condition is false it must do something that cause system reboot. Is it a function call?

    Spontaneously I think there are two options here. Either hide the macros for Cppcheck:

    #define _ASSERT(COND)
    

    Or show Cppcheck that the macros terminate if the condition is false. Like:

    void restart_system(void) __attribute__((noreturn));
    ..
    #define _ASSERT(COND)    if (!(COND)) restart_system();
    
     
  • Daniel Marjamäki

    For information... I get no warning with this code:

    #define COUNT   10
    
    int buf[COUNT];
    
    #define _ASSERT(COND)  if(!(COND)) exit(1)
    
    void f() {
        int x = 100;
       _ASSERT(COUNT > x);
       _ASSERT(buf[x]); 
    }
    
     
  • Jon Read

    Jon Read - 2017-03-06

    Aha - got it. Thanks for the pointer. Yes, there's a function call that reboots the system and it has a noreturn attribute.

    We were checking the condition using the ?: ternary operator, which seems to have misled cppcheck. Replacing this with an if statement resolves the issue.

    Many thanks!
    Jon

     
  • Daniel Marjamäki

    ok then it is a bug in Cppcheck. do you think you could tweak my example code so it looks more like your code and then gives a FP?

     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.