rpatters1
rpatters1

Reputation: 456

Possible Memory Leak with [NSString alloc]

I write plugins for a cross-platform application. My code depends almost entirely on the application's API for interacting with the outside world, which means my experience with the OS-level APIs is limited. But I do have a small amount of OS-specific code to accomplish goals that the application's API does not provide for. On the Mac side I have a number of code snippets like this one that changes the title of a Window:

First a utility function:

NSString *GetNSStringFromUTF16 ( const utf16char * const str )
{
   size_t len = 0;
   while ( str[len] )
      len++;
   NSData* data = [[NSData alloc] initWithBytes:str length:sizeof(*str)*len];
   NSString* retVal = [[NSString alloc] initWithData:data encoding:NSUTF16LittleEndianStringEncoding];
   [data release];
   return retVal;
}

Then later I set the window title like this:

[myWind setTitle:GetNSStringFromUTF16(newTitleStr)];

I was running XCode Analyze and it flagged a number of "possible memory leaks" from calls to my GetNSStringFromUTF16 function. But it did not flag this one. Is it a memory leak or not?

Upvotes: 0

Views: 177

Answers (1)

matt
matt

Reputation: 534925

Don't think. Just follow the Golden Rule: if you said alloc, copy, or retain, you must say release. Did you say alloc? Yes! Then you must say release. You need to autorelease your retVal before you return it.

Other comments: Do not start a method name with a capital letter. And do not start your function name with get! That has an effect on what the analyzer expects the memory management to be.

One last comment: If at all possible use ARC instead of manual memory management.

Upvotes: 2

Related Questions