1

I'm doing a simple exercise to look at the heap and stack using Objective-C.

I create an NSNumber object in main - I'm assuming that this points to the heap, right? When I try to run printf on the object, I get a EXC_BAD_ACCESS error.

  • NSLog works fine - from my understanding, NSLog is printf but extended.
  • I can run a printf on an NSString

In the past I've run printf on objects and it wasn't a problem. Did something change or am I missing something obvious?

When I run the debugger and print out the object, I get the result: isa

        Printing description of lifeAnswerObject:
        (NSNumber) NSNumber = {
            NSValue = {
                NSObject = {
                    isa = <read memory from 0x966d0398ef3e399b failed (0 of 8 bytes read)>

                }
            }
        }

What does this mean? Even though the NSNumber is wrapped in the autoreleasepool it shouldn't be released at this point.

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        NSLog(@"Hello, World!");

        NSNumber *lifeAnswerObject = [[NSNumber alloc] initWithInt: 42];
        NSString *helloWorld = @"Hello out there world";
        NSLog(@"%@ in the heap", lifeAnswerObject);
        // EXC_BAD_ACCESS (code=EXC_I386_GPFLT)
        printf("%s", helloWorld); // survives
        printf("%s", lifeAnswerObject);
        int lifeAnswer = 42;

        printf("%d : in the stack", lifeAnswer);
    }
    return 0;
}

debugger

Romy Ilano
  • 124
  • 1
  • 3
  • 14

1 Answers1

2

This has nothing to do with tagged pointers.

You can’t use %s to print an object type ever. That it survived is merely coincidental; The address of the object happened to not have data that caused it to crash.

Look at the output of the printf() of the string. It is garbage.

If you want to use printf(), you need to supply a char* buffer.

bbum
  • 162,346
  • 23
  • 271
  • 359