Search code examples
c++r

R warning: format string is not a string literal (potentially insecure) [-Wformat-security]


I am receiving a "significant warning" from CRAN on the CLANG compile of ANN.cpp, in the yaImpute package, indicating;

format string is not a string literal (potentially insecure) [-Wformat-security]

I have tracked down the warning to this C++ code block, specifically both calls to Rprintf(msg). However, in reading posts on this warring, I am unclear on exactly how to address the security issue in the print.

void annError(const char *msg, ANNerr level)
{
    if (level == ANNabort) {
      //cerr << "ANN: ERROR------->" << msg << "<-------------ERROR\n";
      Rprintf("ANN Fatal ERROR:");
      Rprintf(msg);
//    std::exit(1);
    }
    else {
      //cerr << "ANN: WARNING----->" << msg << "<-------------WARNING\n";
      Rprintf("ANN WARNING:");
      Rprintf(msg);
    }
}

I have seen advice that using __attribute__((__format__ (__printf__, 2, 0))) is one way to address this issue but am unsure on how to modify the code block. I am admittedly, not a C++ programmer and inherited this code with the yaImpute package. Any advice would be much appreciated.


Solution

  • The format string refers to the first argument of Rprintf, and that should be a string literal:

    Rprintf("ANN WARNING:");
    Rprintf("%s", msg);
    

    Or:

    Rprintf("ANN WARNING:\n%s", msg);
    

    See also the documentation of the -Wformat-security compiler flag in the GCC manual. (Yes, your warning was issued by Clang, but the Clang manual is much less helpful here.)