0
votes

I obtained the following code from the servin.com website. Although the code works, Instruments reports a memory leak. I don't see any alloc, retain, copy in the code so I cannot figure out how to resolve this memory leak. The code & results from Instruments are below. Any help would be appreciated.

// Part 1 - Create Internet socket addr of zero
struct sockaddr_in zeroAddr;
bzero(&zeroAddr, sizeof(zeroAddr));
zeroAddr.sin_len = sizeof(zeroAddr);
zeroAddr.sin_family = AF_INET;

// Part 2- Create target in format need by SCNetwork
SCNetworkReachabilityRef target = 
SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *) &zeroAddr);

// Part 3 - Get the flags
SCNetworkReachabilityFlags flags;
SCNetworkReachabilityGetFlags(target, &flags);

// Part 4 - Create output
NSString *sNetworkReachable;
if (flags & kSCNetworkFlagsReachable)
    sNetworkReachable = @"YES";
else
    sNetworkReachable = @"NO";

NSString *sCellNetwork;
if (flags & kSCNetworkReachabilityFlagsIsWWAN)
    sCellNetwork = @"YES";
else
    sCellNetwork = @"NO";


NSLog (@"Network Reachable: %@", sNetworkReachable);
NSLog (@"Cell Network: %@", sCellNetwork);

Results from Instruments...

Leaked Object - # - Address - Size - Responsible Library - Responsible Frame

Malloc 16 Bytes - 1 - 0x5141d50 - 16 Bytes - SystemConfiguration - SCNetworkReachabilityCreateWithAddress

SCNetworkReachability - 1 - 0x51347b0 - 288 Bytes - SystemConfiguration - SCNetworkReachabilityCreateWithAddress

2

2 Answers

2
votes

The leak is there. After all the code you should release the reference to target. From apple's documentation on SCNetworkReachabilityCreateWithAddress:

Return Value

A new immutable reachability reference. You must release the returned value.

Try using CFRelease(target) function to eliminate the call. If you need the reference to persist between function calls - make it an instance variable in your class.

0
votes

If you read the documentation of SCNetworkReachabilityCreateWithAddresss

Return Value

A new immutable reachability reference. You must release the returned value.