Variational patterns and types of security

There are several implementations of the printf varadic templates function. One of them:

void printf(const char* s) {
  while (*s) {
    if (*s == '%' && *++s != '%') 
      throw std::runtime_error("invalid format string: missing arguments");
    std::cout << *s++;
  }
}

template<typename T, typename... Args>
void printf(const char* s, const T& value, const Args&... args) {
  while (*s) {
    if (*s == '%' && *++s != '%') {
      std::cout << value;
      return printf(++s, args...);
    }
    std::cout << *s++;
  }
  throw std::runtime_error("extra arguments provided to printf");
}

and everywhere they say that this implementation is type safe, while normal C (with va_arg variable arguments) is not.

Why? What does it mean to be type safe and what advantages does this implementation have over C printf va_arg?

+5
source share
2 answers

A safe or secure type means that you can tell by looking at the source code whether your program is working properly.

The statement is std::cout << xalways correct, assuming that it xhas a clearly defined meaning (and is not, say, uninitialized); this is what you can guarantee by looking at the source code.

, C : , , :

int main(int argc, char * argv[])
{
    if (argc == 3)
        printf(argv[1], argv[2]);
}

, , "%s".

, C, , . printf . , , , , , .

+4

, , . . cout operator<<. . , int, ostream::operator<<(int), , ostream::operator<<(double). , . . .

C printf, . . ( ). , . .

, . C printf, , undefined. , , , , .

+5

All Articles