I have been trying to use printf inside a buggy device function as an aid
to debugging it. It appears if I make an error in printf’s formating string,
eg confusing %lu with %d, no error is reported by the compiler nor at runtime
but my (debug) output is in correct.
Has anyone else experienced this?
Has anyone found a work around (other than the totally infeasible do not
make errors;-)
Are there any tools for checking printf before/during/after compiling?
Note that C/C++ compilers are under no obligation to check the consistency of the format string with the other arguments passed to printf().
C/C++ library functions are not built-ins as they may be in other languages, and theoretically you could re-define any one of them in any way you choose. This is the basis of interposer libraries for example that may provide error tracking [e.g. malloc/realloc/free] or profiling functionality, or on occasion just override the vendor version of a function with a local version for higher performance. To facilitate this the DLLs containing the runtime library typically export the symbols with “weak” linkage.
To illustrate the point, the following is perfectly legal C code and should be compiled without complaints by any C compiler (just to be sure I tried the Microsoft and Intel compilers at warning level 3).
#include <stdio.h>
#include <stdlib.h>
int printf (const char *cp, ...)
{
puts ("42\n");
return (int)cp;
}
int main (void)
{
const int a = 43;
printf ("%d", a);
return EXIT_SUCCESS;
}
As an extension to the language standards, some compilers, under certain settings, may treat various library functions as “well-known” functions, and apply extended error checking to emit warnings in the case of printf() or apply optimizations, e.g. replacing calls to pow() with an equivalent sequence of multiplications.
Best I know, at present the CUDA toolchain does not offer such functionality, either for purposes of extended error checking or for performance.
Dear njuffa,
Thank you for your very rapid and helpful reply.
I guess we will all have to be careful.
Its good to know I am not missing anything obvious.
Thanks again
Bill