TOMLKit icon indicating copy to clipboard operation
TOMLKit copied to clipboard

Memory Leaks on iOS `TOMLTable.convert(to:options:)`

Open codingiran opened this issue 1 year ago • 4 comments

My Code is quit simple:


// a toml string
var tomlString = '''
port = 6789
socks_port = 7890
allow_lan = false
bind_address = '*'
log_level = 'debug'
ipv6 = false
tun_fd = 0
'''
// `NetspeedConfig` is a Swift Struct define in my app
var config = try TOMLDecoder().decode(NetspeedConfig.self, from: tomlString)

// set property etc.
config.tun_fd = 10
...

// convert to toml string
tomlString = try TOMLEncoder().encode(config)

// create a TOMLKit table
let table = try TOMLTable(string: tomlString)

// convert to strings
let output_toml = table.convert(to: .toml)
let output_json = table.convert(to: .json)
let output_yaml = table.convert(to: .yaml)

iShot_2024-01-09_16 46 58

Xcode Instruments catch this memory leak, please download it and check in Xcode https://github.com/codingiran/TOMLKit/blob/main/MemoryLeaks/TOMlKit%20Memory%20Leaks.trace.zip

codingiran avatar Jan 09 '24 09:01 codingiran

Unfortunately, quite a few values returned from cpp to Swift are returned via simple malloc or cpp new and never freed

nikitabobko avatar Jan 03 '25 00:01 nikitabobko

There a few probably trivial memory leak fixes?

  • https://github.com/nikitabobko/TOMLKit/commit/b2932ca2f5323cb1336b12d685d713db500bc105
  • https://github.com/nikitabobko/TOMLKit/commit/020d5da50d5ab0088aa1e7d6ac74c5b8478a3a85
  • https://github.com/nikitabobko/TOMLKit/commit/d988ba0c59d7ecf4c6445f4a32118097761a5b21

But the one this issue is about inside TOMLTable.init / tableCreateFromString is slightly more complicated. A simple TOMLTable.deinit cannot be slapped in, because the ownership for tablePointer: OpaquePointer are not immediately trivial to me. The pointer can travel from TOMLTable to TOMLTable.

nikitabobko avatar Jan 03 '25 00:01 nikitabobko

This makes me worried to use😂

xiaowei-dreame avatar Jan 22 '25 01:01 xiaowei-dreame

This makes me worried to use😂

@nikitabobko did fix memory leak, you can try his fork version

codingiran avatar Jan 22 '25 04:01 codingiran