CFNetworkCopyProxiesForAutoConfigurationScript memory leak

The function CFNetworkCopyProxiesForAutoConfigurationScript causes a consistent memory leak.

Simplifying the code provides:
Code Block
var err: Unmanaged<CFError>? = Unmanaged.passRetained(CFErrorCreate(nil, "" as CFErrorDomain, 0, nil))
    let proxiesCFArrayRef = CFNetworkCopyProxiesForAutoConfigurationScript(
      script as CFString,
      self.wsAsHTTPURL as CFURL,
      &err
    )
    err?.release()
    proxiesCFArrayRef?.release()


Which leaks. Is this a bug in CFNetwork or is there another way of clearing the memory allocated ?
Your code definitely leaks the error you set up on line 1. The rules for CFError ‘out’ parameters are as follows:
  • The callee ignores the initial value.

  • The callee must set the value if it fails.

  • The caller must only look at the value if the function result from the callee indicates a failure.

  • The caller must then released that value.

Here’s how I’d wrap this routine to make it easier to call from Swift:

Code Block
func proxies(for url: URL, autoConfigurationScript script: String) throws -> [[String: Any]] {
var errorCFQ: Unmanaged<CFError>? = nil
guard let proxies = CFNetworkCopyProxiesForAutoConfigurationScript(
script as CFString,
url as CFURL,
&errorCFQ
)?.takeRetainedValue() else {
let error = errorCFQ!.takeRetainedValue() as Error
throw error
}
return proxies as! [[String: Any]]
}


IMPORTANT While your code definitely leaks, fixing that leak may not fix all the leaks. It would not surprise me if CFNetworkCopyProxiesForAutoConfigurationScript had its own internal leaks.

Oh, and what are you calling this routine for? I generally encourage folks to use high-level APIs, like URLSession and Network framework, that deal with proxies automatically.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
CFNetworkCopyProxiesForAutoConfigurationScript memory leak
 
 
Q