What is wrong with this code?
#include <stdio.h>
#include <stdarg.h>
void myprintf(const char * format, ...) __printflike(1, 2);
int main(int argc, const char * argv[]) {
printf("%s\n");
myprintf("%s\n");
return 0;
}
void myprintf(const char * format, ...) {
if (format) {
va_list arguments;
va_start(arguments, format);
vprintf(format, arguments);
va_end(arguments);
}
}
By using __printflike
I get a nice warning, like printf
. But unlike printf
, which prints trash at least, I get EXC_BAD_ACCESS on the call to vprintf
as shown here:
Is there any way I can make this work? Thanks!
UPDATE: I understand that by calling a function with the wrong number of arguments I get undefined behavior, but I'd like myprintf
to behave just like printf
does (without crashing). Is that possible? Is there any way I can check the arguments before calling vprintf
to avoid the exception?
UPDATE 2: I think I got it now, thanks for all the comments and answers. For this very simple example I think is better to use a macro, which fails fast and crashes at the calling point: