Skip to content

Instantly share code, notes, and snippets.

@danilaml
Last active August 26, 2015 23:50
Show Gist options
  • Save danilaml/00c4b1d877b35b5354e6 to your computer and use it in GitHub Desktop.
Save danilaml/00c4b1d877b35b5354e6 to your computer and use it in GitHub Desktop.
template<typename... Args> safe_buffers std::string format(const char* fmt, Args... args)
{
std::unique_ptr<char[]> buf(new char[4096]);
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wformat-security"
const std::size_t len = snprintf(buf.get(), 4096, fmt, do_unveil(args)...) + 1;
if (len > 4096) {
buf.reset(new char[len]);
snprintf(buf.get(), len, fmt, do_unveil(args)...);
}
#pragma GCC diagnostic pop
if (len > INT_MAX)
{
throw std::runtime_error("std::snprintf() failed");
}
return { buf.get(), buf.get() + len - 1};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment