Malloc() Struct with NSString Inside?
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?
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?
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).
Don't ever call free on an NSObject
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.
Possibly Related Threads...
| Thread: | Author | Replies: | Views: | Last Post | |
| A few pixels inside | Miglu | 3 | 2,941 |
Aug 12, 2010 07:41 PM Last Post: Miglu |
|
| error: malloc.h: No such file or directory | tehqin | 2 | 6,009 |
Mar 11, 2007 03:03 AM Last Post: mac_girl |
|
| Struct based functions | Jones | 9 | 4,484 |
May 9, 2006 02:37 PM Last Post: Zekaric |
|
| Can't use NSString to put a number on screen? | kensuguro | 3 | 4,198 |
Nov 7, 2005 01:16 AM Last Post: Jordan |
|
| Getting Number From Character In NSString | Nick | 2 | 3,816 |
Oct 31, 2005 10:08 AM Last Post: Nick |
|

