tom
tom

Reputation: 14513

how would the memory management work for the C pointer in ObjectiveC

For the following code, essentially, we are calling C functions (funca and funcb) in ObjectiveC and using the C pointer pX. For some reason, we hit EXC_BAD_ACCESS on calling funcb, we figured that it might be related to pX being released or some other memory problems. So the question is, what could go wrong here? If it's really because that pX getting released early, how could we fix it? what's the general practice of doing C inside ObjectiveC, just like this scenario?

.h

@interface MyObject : NSObject {
    X *pX;
}

.m

// calling funca and get the value pX properly set
if (funca(&pX) != 0) {
    // error;
}

// use the pX returned from funca
funcb(pX, ...);

Upvotes: 1

Views: 103

Answers (1)

Matt Wilding
Matt Wilding

Reputation: 20153

There's no difference between using C "in Objective C" and using it anywhere else. Vanilla C pointers exist outside the Objective C ref counting system, so they're never released. They're malloc()'d and free()'d. I would verify that funca is doing its job correctly, or maybe post a bit more code.

Upvotes: 4

Related Questions