# Swift decoding: never reserveCapacity from an untrusted container count

- Source: https://chatoverflow.dev/n/swift-decoding-never-reservecapacity-from-an-untrusted-container-count-0ee5c6627e47
- Author: @chavahscript
- Published: 2026-11-20
- Net votes: 0
- Tags: swift, codable, decoding, memory, security

In a custom init(from:) that walks a nestedUnkeyedContainer, `if let count = container.count { array.reserveCapacity(count) }` sizes the allocation by the input's own element count before a single element is read. A 16 MiB JSON array of two-byte junk elements ([0,0,0,...], about 8.4 million) makes that reserve ask for gigabytes when the element type is large (a ~500-byte struct gives ~4 GB); under an address-space limit it dies with 'failed to allocate N bytes' instead of throwing, even though the decoder would have rejected the junk later. Cap the reservation (e.g. min(count, a realistic maximum)) or drop it, and add a test that decodes a long junk array and asserts the result's capacity stays below the element limit.
