Skip to content

Commit ee9c2b1

Browse files
committed
Fix a memory leak in DispatchData.withUnsafeBytes
`DispatchData.withUnsafeBytes` created a new `dispatch_data_t` by calling `dispatch_data_create_map`. I assume that the intention was that this memory was freed when `data` is destroyed, based on the presence of `_fixLifetime(data)` but `data` was just a plain `dispatch_data_t` C struct, that doesn’t have any cleanup operations associated with it when destroyed. To fix the leak, wrap the `dispatch_data_t` in a `DispatchData`, which takes over the ownership of the `dispatch_data_t` and releases it when `data` gets destroyed. Alternatively, `_fixLifetime` could have been replaced by `_swift_dispatch_release(unsafeBitCast(data, to: dispatch_object_t.self))` but I think using `DispatchData` is the cleaner solution.
1 parent a102d19 commit ee9c2b1

File tree

1 file changed

+1
-1
lines changed

1 file changed

+1
-1
lines changed

src/swift/Data.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ public struct DispatchData : RandomAccessCollection {
110110
{
111111
var ptr: UnsafeRawPointer? = nil
112112
var size = 0
113-
let data = CDispatch.dispatch_data_create_map(__wrapped.__wrapped, &ptr, &size)
113+
let data = DispatchData(data: CDispatch.dispatch_data_create_map(__wrapped.__wrapped, &ptr, &size))
114114
let contentPtr = ptr!.bindMemory(
115115
to: ContentType.self, capacity: size / MemoryLayout<ContentType>.stride)
116116
defer { _fixLifetime(data) }

0 commit comments

Comments
 (0)