How to use custom asserts with C++

Hi,

I’m currently using SonarQube 2025.1 LTA (Enterprise) with C++ codebase. I’ve noticed that analysis ignores information about possible values for variables that are given through custom asserts. So, for example, it creates issues for out-of-bounds access for cases like this:

MY_CUSTOM_ASSERT(idx == 0 || idx == 1);
ar[idx] = value; << Access of the field 'ar' at an overflowing index, while it hold only 2 'long' elements

Is there some recommended way how to deal with this? Maybe there is some compile definition that I can use in my code to replace implementation of assert with std::terminate just for SonarQube analysis?

Welcome back @Nekto,

It depends on how the MY_CUSTOM_ASSERT macro is defined.
If the macro expands into like a ternary-expression where one branch calls a function that has a noreturn attribute, then it should work - assuming that build-wrapper captured the build commands where the MY_CUSTOM_ASSERT macro was not expanded to nothing.

One case that we don’t handle well is asserts that call conditionally noreturn functions. For example:

/// Log the message into a file if level is zero.
/// Abort if level is one.
void log_or_abort_impl(int level, const char *msg);

#DEFINE log_or_abort(LEVEL, COND) do { if (COND) log_or_abort_impl(LEVEL, #COND); } while (false)
#define FATAL 1

void my_fn(int idx) {
  log_or_abort(FATAL, idx == 0 || idx == 1);
  ar[idx] = value; << Access of the field 'ar' at an overflowing index, while it hold only 2 'long' elements
}

In this case, as log_or_abort_impl does not have the noreturn attribute (nor it should), we would think that both paths are possible: reach the array access when the condition idx == 0 || idx == 1 is true and also when it’s false; thus report the FP.

I could only tell what’s behind this if I’d know how the MY_CUSTOM_ASSERT is implemented.

You can send me a reproducer for investigation if this didn’t help.
To generate the reproducer file:

  • Search in the analysis log for the full path of the source file for which you want to create a reproducer (for instance, a file that contains a false-positive). You will have to use exactly this name (same case, / or \…)
  • Add the reproducer option to the scanner configuration:
    sonar.cfamily.reproducer=“Full path to the .source file”
  • Re-run the scanner to generate a file named sonar-cfamily-reproducer.zip in the project folder.
  • Please share this file. If you think this file contains private information, let us know, and we’ll send you a private message that will allow you to send it privately.