Menu

Discourage assert()

mcandre
2019-01-11
2023-06-01
  • mcandre

    mcandre - 2019-01-11

    Modern C/C++ programming prefers perror() or returning error values, to using assert(). I understand this is because assert() often becomes a NOP in release binaries, and assert() can occasionally leak sensitive information.

    Given that assert() is now frowned upon, could cppcheck update its rule checks to recommend suitable replacements in our source code files?

     
  • Daniel Marjamäki

    I have not heard that assert() should be avoided. If you have some references let me know.

    For now I am skeptic about writing a rule in Cppcheck. You could create your own rule file for this easily.

    Personally I do not agree that assert should be avoided, but well I do not agree about all best practices.

     
  • Christopher Yeleighton

    We should check that assertions are not used to assert environment-dependent conditions.

     
    • Andrew C Aitchison

      Do you mean environment variables or the build or run platform ?

      If I write code that I know does not work on 64 bit architectures, and someone compiles it for a 64bit machine I would like the user to be told.

       
      • Daniel Marjamäki

        If I write code that I know does not work on 64 bit architectures, and someone compiles it for a 64bit machine I would like the user to be told.

        yes I agree however that would ideally be asserted at compile time so it can't be built.

        as I understand this discussion it's about asserts at runtime.

         
  • Daniel Marjamäki

    The MSC-11 says:

    Assertions should never be used to verify the absence of runtime (as opposed to logic) errors, such as

    Invalid user input (including command-line arguments and environment variables)
    File errors (for example, errors opening, reading or writing files)
    Network errors (including network protocol errors)
    Out-of-memory conditions (for example, malloc() or similar failures)
    System resource exhaustion (for example, out-of-file descriptors, processes, threads)
    System call errors (for example, errors executing files, locking or unlocking mutexes)
    Invalid permissions (for example, file, memory, user)

    I don't know.. if there is for instance out of memory it might often be reasonable to just terminate directly. If you want to terminate directly then what is bad about an assert() ? The problem would be if the assert() is removed in release builds and you rely on it.. but there is no requirement to remove asserts in release builds.

     

    Last edit: Daniel Marjamäki 2023-06-01

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.