cromandini cromandini - 15 days ago 5
C Question

EXC_BAD_ACCESS when calling vprintf()

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:

enter image description 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:

enter image description here

Answer

Undefined means unpredictable. In one run printf may produce trash, in another it may produce EXC_BAD_ACCESS instead. You cannot reproduce undefined behavior. In this particular case, the %s term in the formatting string says printf need to find a C-string. Depending on your libc implementation, when you did not specify the second argument, it may find it somewhere. And if it happens that a null character is found not far away from this pointer, you get trash output. If not, printf will continue to search the end of the string until it gets out of range of the memory assigned to your program and you get the EXC_BAD_ACCESS.

Comments