Coverity analysis shows error with const type. How to resolve this?

588 Views Asked by At

When I am running Coverity analysis shows error in function below.

void initalizeStatement(sqlite3* db, const char* query)
{
    // statement shall not be reuesed!
    if (_valid) _valid = false;
    else
    {
        sqlite3_stmt* stmt = NULL;
        auto result = sqlite3_prepare(db, query, -1, &stmt, NULL);

        if(SQLITE_OK != result)
        {
            DLT_LOG(dltContextSARMBUtils, DLT_LOG_ERROR,
                   DLT_STRING("[Statement::initalizeStatement()] sqlite3_prepare failed. status code : "),
                   DLT_INT(result),
                   DLT_STRING(", query : "),
                   DLT_STRING(query));
        }

        else //all good!
        {
            _valid = true;
            _stmt = stmt;
            _db = db;
        }
    }
}

Error I am seeing is as below:

<testcase name="[45] MISRA C++-2008 Rule 7-1-1 | misra_cpp_2008_rule_7_1_1_violation" time="0">
<failure message="The variable `query` has a non-const type, however its value is never changed. Consider adding a const qualifier to the variable type."> MBUtils::Statement::initalizeStatement(sqlite3*, char const*) </failure>

Why is this error shown if it is already having const type?

1

There are 1 best solutions below

0
On

Solution: Add const to the declaration

MISRA C++ 2008 Rule 7-1-1 reads, in its entirety, "A variable which is not modified shall be const qualified." (The standard is not freely available so I can't link to it.) Additionally, the example given in the standard makes it clear that this rule applies to parameters as well as local variables.

In your example code, query is not modified, hence it must be const qualified to comply with this rule:

void initalizeStatement(sqlite3* db, const char* const query)
//                                               ^^^^^ added

In your original code, query is declared to point to something that is const, but is not itself const.

How to read C declarations

As the syntax for C/C++ declarations can be a bit confusing, my advice is to read them from right to left. So the original declaration:

const char * query

would be read as "query is a pointer to a character that is constant". The declaration in my suggested fix:

const char * const query

would be read as "query is a constant pointer to a character that is constant".

Style opinion

Incidentally, if this were my code (and I had to comply with MISRA), I would actually write it as:

char const * const query

This reverses the order of char and const at the beginning, so it now reads as "query is a constant pointer to a constant character", which is a more natural English description.