views:

78

answers:

2

I have the following code:

eachShape(void *ptr, void* unused) {
  cpShape *shape = (cpShape *) ptr;
  id obj = shape->data;
  NSLog(@"shape->data: %@", obj);  // this is where EXC_BAD_ACCESS can occur
  ...

Some of you may recognize it from the Chipmunk physics framework used in iPhone development. Basically I crash here because of something I am doing in other code regarding the cpSpace, but I want to figure out what object type is getting sent here and crashing my NSLog statement (and causing other havoc).

What is the best way to dump the type and/or contents from a void pointer to an NSLog call?

+1  A: 

I think your problem is that %@ is only meaningful if shape->data really points to an Objective-C object, since using it triggers the sending of -description to obj. But if for example shape->data points to an int, the message will be send to an object that does not really exists. Instead, some memory location may be interpreted as the raw bytes of an object, causing the runtime to crash.

To answer your question: The type of an void pointer is void *, and the type of the pointer's target is void. You can print the pointer's value with %p, but I doubt that this is what you want.

So if you are sure that the memory location where shape->data points to represents an Objective-C object, and you have access to the class code, you can override -description to print whatever information you like.

swegi
Thanks for the advice!
Greg
+1  A: 

The %@ format specifier is interpreted as

Objective-C object, printed as the string returned by descriptionWithLocale: if available, or description otherwise. Also works with CFTypeRef objects, returning the result of the CFCopyDescription function.

Basically, if ptr doesn't point to an Objective-C object, you're out of luck!

Either way, you should cast the void * pointer to something meaningful..

Adam Woś
Thanks for the advice!
Greg