Re: UInt8 > NSString
Re: UInt8 > NSString
- Subject: Re: UInt8 > NSString
- From: Bob Smith <email@hidden>
- Date: Mon, 5 Mar 2007 20:18:27 -0800
On Mar 5, 2007, at 3:47 PM, arri wrote:
On Mar 5, 2007, at 21:22 31, Bob Smith wrote:
The suggestion from others to return an NSString * instead is the
better solution. But just so you know, the problem here is a
basic C memory management error. Your function is returning an
automatic variable, which becomes undefined out of scope of the
function. What you need to do is change:
char addr[12]
to
static char addr[12]
and it would work.
i guess that that is why i was getting getting this --function
returns address of local variable-- warning?
Yes, exactly. The compiler was warning you that the function was
returning a pointer to memory that would not still be valid in the
code which called the function. The reason it worked sometimes and
not others was just because the memory wasn't always being used for
something else immediately; but you can't ever rely on that.
However this is not thread-safe since the same static space would
be used in any thread calling the function.
Hope this helps!
yes, it helps:) as i wrote, i implemented the main-function as an
obj-c method
of the class that was calling the function. this methods then calls
the statically declared functions
and creates an NSString from the returned bytes. seems perfectly
threadsafe.
Hmmm, maybe, I would have to see your code to be sure. Briefly, here
is the thread-safe approach:
- (NSString *)makeTheString
{
char theBytes[10];
(do something to fill in theBytes)
NSString *theString = [NSString stringWithCString:theBytes];
return(theString);
}
Safe, because theBytes[] is dynamically allocated each time the
method is called; which is why you were having your original problem,
but now it's a good thing because it means each thread will have it's
own memory. However here is the not-thread-safe version:
- (NSString *)makeTheString
{
char *theBytes = getTheStringBytes();
NSString *theString = [NSString stringWithCString:theBytes];
}
.
.
.
static char *getTheStringBytes()
{
static char theBytes[10];
(do something to fill in theBytes)
return(theBytes);
}
Not safe, because theBytes[] is pre-allocated by the compiler so all
threads would try to use the same memory.
Bob S.
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden