See what's going on with flipcode!




This section of the archives stores flipcode's complete Developer Toolbox collection, featuring a variety of mini-articles and source code contributions from our readers.

 

  Unchecked Printf Parameters
  Submitted by



Some strange people like me code in C++ but still continue to use the printf() function to log. Variable parameters are useful and easy to use, check is not done on most compilers.

If you write something like this:

std::string cmd;
Log("my command is %s", cmd);  



You are sure to have problems when this code is executed. On Microsoft Visual C++, there's no warning displayed and at execution time, it'll display a strange string and can crash.

gcc does a check and displays a warning at compilation time but crashes if this code is executed (really bad if you didn't see the warning).

Now, look at we can do using templates:

// With one parameter, there's no problem

inline void Log(const char *fmt) { printf(fmt); }

// With 2 parameters, we check with a template function template<class A

void Log(const char *fmt, A a) { CheckLogType(a); printf(fmt, a); }

// With 3 parameters, we check with a template function template<class A, class B

void Log(const char *fmt, A a, B b) { CheckLogType(a); CheckLogType(b); printf(fmt, a, b); }

// And we continue with 4, 5, 6, ... 26 parameters if you want

// We have just now to implement CheckLogType with acceptable types inline void CheckLogType (int a) { }

inline void CheckLogType (unsigned int a) { } inline void CheckLogType (char a) { }

inline void CheckLogType (unsigned char a) { } inline void CheckLogType (long a) { }

inline void CheckLogType (unsigned long a) { } inline void CheckLogType (float a) { }

inline void CheckLogType (double a) { } inline void CheckLogType (const char *a) { }

inline void CheckLogType (const void *a) { }



Now if you forget a .c_str() in a std::string in your code or you try to put an argument in Log() call that is not valid, the compiler will generate an error because no CheckLogType() will be found with your type to instantiate the Log template function.

If you are frightened with the compilation time and execution time or space, you can just activate this piece of code in debug mode and just do a Log() function without any checks in release mode.

Hope you'll like

Vianney "Ace" Lecroart

The zip file viewer built into the Developer Toolbox made use of the zlib library, as well as the zlibdll source additions.

 

Copyright 1999-2008 (C) FLIPCODE.COM and/or the original content author(s). All rights reserved.
Please read our Terms, Conditions, and Privacy information.