Skip to content

Make sure to free the malloced pointer even in case of throwing an error #1394

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 1, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 14 additions & 8 deletions Sources/FoundationEssentials/Data/Data+Base64.swift
Original file line number Diff line number Diff line change
Expand Up @@ -490,15 +490,21 @@ extension Base64 {
let other = pointer?.bindMemory(to: UInt8.self, capacity: outputLength)
let target = UnsafeMutableBufferPointer(start: other, count: outputLength)
var length = outputLength
if options.contains(.ignoreUnknownCharacters) {
try Self._decodeIgnoringErrors(from: inBuffer, into: target, length: &length, options: options)
} else {
// for whatever reason I can see this being 10% faster for larger payloads. Maybe better
// branch prediction?
try self._decode(from: inBuffer, into: target, length: &length, options: options)
do {
if options.contains(.ignoreUnknownCharacters) {
try Self._decodeIgnoringErrors(from: inBuffer, into: target, length: &length, options: options)
} else {
// for whatever reason I can see this being 10% faster for larger payloads. Maybe better
// branch prediction?
try self._decode(from: inBuffer, into: target, length: &length, options: options)
}

return Data(bytesNoCopy: pointer!, count: length, deallocator: .free)
} catch {
// Do not leak the malloc on error
free(pointer)
throw error
}

return Data(bytesNoCopy: pointer!, count: length, deallocator: .free)
}

static func _decode(
Expand Down