randomqsns
randomqsns

Reputation: 11

Is it still safe to use snprintf function in C++?

Confused when trying to research about the use of snprintf in C++. I see some online recommends the use of snprintf over sprintf as below.

snprintf(str, sizeof(str), "%s", message); 

while some online says would need additional check when snprintf is used as below.

int main(int argc, char *argv[])
{
    char buffer[BUF_SIZE];
    size_t pos = 0;
    int i;
 
    for (i = 0; i < argc; i++)
    {
        int n = snprintf(buffer + pos, BUF_SIZE - pos, "%s", argv[i]);
        if (n < 0 || n >= BUF_SIZE - pos)
        {
            break;
        }
        pos += n;
    }
}

Appreciate your thoughts. Thanks

Upvotes: 1

Views: 243

Answers (1)

Aykhan Hagverdili
Aykhan Hagverdili

Reputation: 29985

You should instead use {fmt}. It's much safer and easier to use. See this example.

#include <fmt/core.h>

int main() {
  std::string s = fmt::format("I'd rather be {1} than {0}.", "right", "happy");
  fmt::print("{}", s);
}

This library is mostly standardized in C++20 as std::format, but no standard libraries support the standard version yet.

Upvotes: 3

Related Questions