Malloc() Struct with NSString Inside?

Member
Posts: 23
Joined: 2007.12
Post: #1
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?
Quote this message in a reply
Member
Posts: 144
Joined: 2009.11
Post: #2
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).

Everyone's favourite forum lurker!
https://github.com/NSError
Quote this message in a reply
⌘-R in Chief
Posts: 1,265
Joined: 2002.05
Post: #3
Don't ever call free on an NSObject
Quote this message in a reply
Member
Posts: 144
Joined: 2009.11
Post: #4
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.

Everyone's favourite forum lurker!
https://github.com/NSError
Quote this message in a reply
Post Reply 

Possibly Related Threads...
Thread: Author Replies: Views: Last Post
  A few pixels inside Miglu 3 3,487 Aug 12, 2010 07:41 PM
Last Post: Miglu
  error: malloc.h: No such file or directory tehqin 2 8,201 Mar 11, 2007 03:03 AM
Last Post: mac_girl
  Struct based functions Jones 9 5,836 May 9, 2006 02:37 PM
Last Post: Zekaric
  Can't use NSString to put a number on screen? kensuguro 3 5,119 Nov 7, 2005 01:16 AM
Last Post: Jordan
  Getting Number From Character In NSString Nick 2 4,565 Oct 31, 2005 10:08 AM
Last Post: Nick