iDevGames Forums
Malloc() Struct with NSString Inside? - Printable Version

+- iDevGames Forums (http://www.idevgames.com/forums)
+-- Forum: Development Zone (/forum-3.html)
+--- Forum: Game Programming Fundamentals (/forum-7.html)
+--- Thread: Malloc() Struct with NSString Inside? (/thread-395.html)



Malloc() Struct with NSString Inside? - Graphic Ace - Jan 26, 2010 04:42 PM

I'm creating a Text based struct

typedef struct theText {
NSString *text;
GLint a,b;
}textBase;

textBase *objText;

objText = malloc(sizeof(textBase));

will there be any problem's with doing this considering NSObject's have there own method for Allocating & Freeing memory?


Malloc() Struct with NSString Inside? - cmiller - Jan 26, 2010 05:04 PM

Graphic Ace Wrote:I'm creating a Text based struct

typedef struct theText {
NSString *text;
GLint a,b;
}textBase;

textBase *objText;

objText = malloc(sizeof(textBase));

will there be any problem's with doing this considering NSObject's have there own method for Allocating & Freeing memory?

In textBase, text is a pointer to an NSString. The allocated memory will be the size of a memory address, plus two GLints. So, to malloc it is quite right. However, when you call free, it will not release text.

I would suggest a simple solution:

Code:
static inline
textBase* createTextBaseRef() {
    return (textBase*)malloc(sizeof(textBase));
}
static inline
void freeTextBase(textBase* ref) {
    [ref->text free];
    free(ref);
}

(forgive my rusty pointer arithmetic - I've been using Ruby lately for work, and so I'm a little out of practice).


Malloc() Struct with NSString Inside? - SethWillits - Jan 26, 2010 05:23 PM

Don't ever call free on an NSObject


Malloc() Struct with NSString Inside? - cmiller - Jan 26, 2010 05:32 PM

FreakSoftware Wrote:Don't ever call ->free on an NSObject

Thanks. Obviously what I was trying to say (and failed miserably) was:

Code:
static inline
textBase* createTextBaseRef() {
    return (textBase*)malloc(sizeof(textBase));
}
static inline
void freeTextBase(textBase* ref) {
    [ref->text release];
    free(ref);
}

As Seth said, if you call free on an NSObject, you're in for some trouble. If you have to use free, then you probably aren't using the retain-release paradigm correctly anyways and so should spend some time with the memory management guide.