SQLite Forum

Access Violation running FTS5 rank due to compiler over-optimization
Login
Embarcadero's C++ Builder may optimize out `rc==SQLITE_OK` in this for loop: <https://www.sqlite.org/src/info?name=afe8c2394cf6de2a&ln=676>
  
This leads to an AV in the same line if `pData` is NULL. This test then crashes: <https://www.sqlite.org/src/info?name=4a15fb03b6c7eac6&ln=90-92>
  
The cause may be an over-optimization or compiler bug. It seems related to the fact that the rc variable is not used within the for loop. This similar loop a few lines above uses rc, and `rc==SQLITE_OK` is compiled in: <https://www.sqlite.org/src/info?name=afe8c2394cf6de2a&ln=659>

It helps to move the [for loop](https://www.sqlite.org/src/info?name=afe8c2394cf6de2a&ln=675-681) into the [`if( rc==SQLITE_OK )`](https://www.sqlite.org/src/info?name=afe8c2394cf6de2a&ln=668-673) block above. This also removes one `rc==SQLITE_OK` test. Another such test may be avoided if the [test below](https://www.sqlite.org/src/info?name=afe8c2394cf6de2a&ln=683-689) is also moved there.

The resulting code looks like this and tests fine:

```C
  /* Figure out the total size of the current row in tokens. */
  if( rc==SQLITE_OK ){
    int nTok;
    rc = pApi->xColumnSize(pFts, -1, &nTok);
    D = (double)nTok;

    /* Determine the BM25 score for the current row. */
    for(i=0; i<pData->nPhrase; i++){
      score += pData->aIDF[i] * (
        ( aFreq[i] * (k1 + 1.0) ) /
        ( aFreq[i] + k1 * (1 - b + b * D / pData->avgdl) )
      );
    }

    /* If no error has occurred, return the calculated score. Otherwise,
    ** throw an SQL exception.  */
    sqlite3_result_double(pCtx, -1.0 * score);
  }else{
    sqlite3_result_error_code(pCtx, rc);
  }
```