Skip to content

Commit 6a7f64f

Browse files
authored
Make sure to free the malloced pointer even in case of throwing an error. (#1394)
Resolves rdar://154702045
1 parent bca5d3d commit 6a7f64f

File tree

1 file changed

+14
-8
lines changed

1 file changed

+14
-8
lines changed

Sources/FoundationEssentials/Data/Data+Base64.swift

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -490,15 +490,21 @@ extension Base64 {
490490
let other = pointer?.bindMemory(to: UInt8.self, capacity: outputLength)
491491
let target = UnsafeMutableBufferPointer(start: other, count: outputLength)
492492
var length = outputLength
493-
if options.contains(.ignoreUnknownCharacters) {
494-
try Self._decodeIgnoringErrors(from: inBuffer, into: target, length: &length, options: options)
495-
} else {
496-
// for whatever reason I can see this being 10% faster for larger payloads. Maybe better
497-
// branch prediction?
498-
try self._decode(from: inBuffer, into: target, length: &length, options: options)
493+
do {
494+
if options.contains(.ignoreUnknownCharacters) {
495+
try Self._decodeIgnoringErrors(from: inBuffer, into: target, length: &length, options: options)
496+
} else {
497+
// for whatever reason I can see this being 10% faster for larger payloads. Maybe better
498+
// branch prediction?
499+
try self._decode(from: inBuffer, into: target, length: &length, options: options)
500+
}
501+
502+
return Data(bytesNoCopy: pointer!, count: length, deallocator: .free)
503+
} catch {
504+
// Do not leak the malloc on error
505+
free(pointer)
506+
throw error
499507
}
500-
501-
return Data(bytesNoCopy: pointer!, count: length, deallocator: .free)
502508
}
503509

504510
static func _decode(

0 commit comments

Comments
 (0)