cromandini cromandini - 1 year ago 63
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[]) {
return 0;

void myprintf(const char * format, ...) {
if (format) {
va_list arguments;
va_start(arguments, format);
vprintf(format, arguments);

By using
I get a nice warning, like
. But unlike
, which prints trash at least, I get EXC_BAD_ACCESS on the call to
as shown here:

enter image description here

Is there any way I can make this work?

UPDATE: I understand that by calling a function with the wrong number of arguments I get undefined behavior, but I'd like
to behave just like
does (without crashing). Is that possible? Is there any way I can check the arguments before calling
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download