Re: Initializing an Array
Re: Initializing an Array
- Subject: Re: Initializing an Array
- From: Simon Stapleton <email@hidden>
- Date: Wed, 23 Jan 2002 10:23:31 +0000 (GMT)
>
Subject: Re: Initializing an Array
>
From: Jeff Galyan <email@hidden>
>
To: "John C. Randolph" <email@hidden>
>
CC: Marcel Weiher <email@hidden>, cocoa-dev
>
<email@hidden>
>
>
On 1/22/02 2:35 PM, "John C. Randolph" <email@hidden> wrote:
>
>
>
>
> On Tuesday, January 22, 2002, at 01:19 PM, Jeff Galyan wrote:
>
>> Well, here's the rub: when I malloc or calloc something and
>
>> then free it
>
>> after use (in Cocoa, and after ensuring it's non-NULL), I get a
>
>> segfault
>
>> when the ObjC runtime tries to free it again.
>
>
>
> Well, of course. If you want NSObject's -dealloc method to free
>
> some memory, you shouldn't be doing it, too.
>
>
>
> It sounds like your problem is a result of mixing malloc() with
>
> +alloc. If you're allocating storage for an Obj-C instance,
>
> don't use malloc(), use +alloc. If you want an
>
> arbitrarily-sized block of bytes, try using NSData and
>
> NSMutableData.
>
>
>
I wish this were the case - that would make my life so much easier.
>
What I'm doing is inside each method, I calloc a char* the length
>
of the NSString (by calling -length to get the length), pass it to
>
-getCString: and then pass the char* to a function in a C++
>
library. When I'm done with the char*, and before the method exits,
>
if I free it (even after verifying it's not a pointer to NULL), the
>
app crashes. If I don't, then the runtime whines at me about
>
attempts to free a pointer not malloced, but it doesn't crash.
OK, everyone else has had a pop, so I might as well...
My guess is threefold, as follows:
If you're only using the c string within the context of the method
(i.e. you allocate it, assign it, pass it to your C++ function,
return from that, dealloc it, and return), use cString, not
getCString. This will safely deallocate your string for you. No
need to malloc/calloc/whatever.
Be sure your C++ function doesn't expect the string to stay around.
And finally, this is what I think your problem is - [aString length]
returns the length of the string, in characters. A 'C' string will be
[aString length] + 1 characters long. Indeed, NSString has
a 'cStringLength' method. Remember the null terminator. You're
stomping on memory, with a nil value. Why are ivars going nil?
Three guesses.
Simon
--
PGP Key ID : 0x50D0698D
--
If the answer isn't obvious, the question is a distraction. Go find
an easier question.