skip to content

With .NET's ArrayPool<byte>.Shared, why can Rent(50_000) return a 65,536-byte array holding old data, and what must the caller track?

level: middleimportance: should knowfreq 42%

answer

  1. at least, never exactly
  2. power-of-two buckets
  3. Return leaves contents by default
  4. keep your own count

basics

~20 s

ArrayPool<byte>.Shared rounds requests up to power-of-two buckets and reuses returned arrays without clearing them, so Rent(50_000) can return 65,536 bytes with a previous renter's data. The caller must track how many bytes it actually uses.

solid answer

~40 s

`ArrayPool<T>.Rent(int minimumLength)` promises an array *at least* that long. The shared pool keeps buckets of power-of-two lengths starting at 16, so a request for 50,000 is served from the 65,536 bucket, and when that bucket is empty it allocates a full 65,536-element array so it can be returned later. Reused arrays are not cleared: `Return(T[] array, bool clearArray = false)` leaves the contents unless you pass `clearArray: true`, and newly allocated ones come from `GC.AllocateUninitializedArray<T>`, so even those are not promised to be zeroed. The caller keeps its own length, the size it needed or the count `Stream.ReadAsync` returned, and works on `buffer.AsSpan(0, count)` or `buffer.AsMemory(0, count)`, never on `buffer.Length` or the whole array.

code

csharp · 18 lines
csharp
using System.Buffers;

byte[] first = ArrayPool<byte>.Shared.Rent(50_000);
Console.WriteLine($"asked 50000, got {first.Length}");
first.AsSpan(0, 5).Fill(0xAB);
ArrayPool<byte>.Shared.Return(first);

byte[] second = ArrayPool<byte>.Shared.Rent(40_000);
Console.WriteLine($"same array: {ReferenceEquals(first, second)}, second[0] = 0x{second[0]:X2}");
ArrayPool<byte>.Shared.Return(second, clearArray: true);

byte[] third = ArrayPool<byte>.Shared.Rent(40_000);
Console.WriteLine($"after clearArray: third[0] = 0x{third[0]:X2}");
ArrayPool<byte>.Shared.Return(third);

Console.WriteLine($"Rent(0) is Array.Empty: {ReferenceEquals(ArrayPool<byte>.Shared.Rent(0), Array.Empty<byte>())}");
Console.WriteLine($"Rent(10).Length = {ArrayPool<byte>.Shared.Rent(10).Length}");
try { ArrayPool<byte>.Shared.Rent(-1); } catch (Exception e) { Console.WriteLine(e.GetType().Name); }

go deeper

for a junior

Remember the two surprises of a rented array: it can be longer than requested, and it can contain somebody else's old data.

for a middle

Explain the bucket rounding, why Return leaves contents unless clearArray is true, and why every operation must use a slice bounded by your own count.

for a senior

Spot the production bugs: hashing or writing the whole rented array, decoding trailing bytes, and tests that pass only because a fresh process hands out zeroed arrays.

for a principal

Decide when clearing is policy, for buffers that held secrets or personal data, and make bounded slices the reviewed norm instead of relying on clearing.

## What Rent promises `ArrayPool<T>` is the base class library's pool of reusable arrays, in `System.Buffers`. Its contract is stated in the reference source: - `ArrayPool<T>.Rent(int minimumLength)` returns "an array that is at least `minimumLength` in length". The `Shared` pool "may hand back a larger array than was actually requested, but will never hand back a smaller array". - `ArrayPool<T>.Return(T[] array, bool clearArray = false)` gives the array back. Clearing is opt-in: with `clearArray: false`, the default, "the array's contents are left unchanged". So two facts hold for every rental: the array can be longer than you asked for, and its contents are whatever was in it before. ## How the shared pool picks a length `ArrayPool<T>.Shared` keeps **buckets** of power-of-two lengths, starting at 16 (in the .NET 10 source, 27 buckets, up to 2^30 elements). A request is rounded up to the bucket that fits, and when that bucket is empty the pool allocates an array of the bucket's full length, so the array can be returned to it later. | Request | Array you get from `Shared` on .NET 10 | |---|---| | `Rent(0)` | `Array.Empty<T>()` | | `Rent(10)` | length 16 | | `Rent(1000)` | length 1024 | | `Rent(50_000)` | length 65,536 | | `Rent(65_536)` | length 65,536 | | `Rent(-1)` | throws `ArgumentOutOfRangeException` | A request larger than the biggest bucket is allocated at exactly the requested length and simply dropped when returned. A private pool from `ArrayPool<T>.Create()` uses the same power-of-two buckets (by default up to 1024 * 1024 elements, 50 arrays per bucket) and may even serve a request from the next bucket up when its own is empty. Code must therefore never assume a particular length. ## Why the array is dirty - **Reused arrays are not cleared.** When you rent, you may get the exact array another component returned a moment ago, with its bytes intact. On a single thread the shared pool keeps the last returned array of each size in a per-thread slot, so the next `Rent` of that size usually gets it straight back. - **New arrays are not promised to be zeroed either.** When the shared pool has to allocate, it calls `GC.AllocateUninitializedArray<T>`, which may skip zeroing for large arrays of types without references. - **`clearArray: true` clears on `Return`**, before the pool stores the array, so the next renter sees zeros. It costs a full `Array.Clear` of the whole array. ## Tracking the real length The caller is the only one who knows how much of the array is meaningful, so it keeps that number itself: 1. Remember the length you asked for, or better, the count an operation reports, such as the `int` that `Stream.ReadAsync` returns. 2. Work on `buffer.AsSpan(0, count)` or `buffer.AsMemory(0, count)` from then on. 3. Never use `buffer.Length`, `foreach` over the whole array, `buffer.ToArray()` or an overload that takes the bare array, because each of those touches the slack and the stale bytes. In the upload service, the loop looks like this: ```csharp byte[] buffer = ArrayPool<byte>.Shared.Rent(64 * 1024); try { int read; while ((read = await source.ReadAsync(buffer.AsMemory(0, 64 * 1024))) > 0) { hash.AppendData(buffer, 0, read); // not hash.AppendData(buffer) await target.WriteAsync(buffer.AsMemory(0, read)); // not target.WriteAsync(buffer) } } finally { ArrayPool<byte>.Shared.Return(buffer); } ``` A version that hashes `buffer` instead of the first `read` bytes produces a wrong hash on every short read, and one that forwards the whole array sends up to 64 KB of another upload's data. Note that the request size, 64 KB, is passed explicitly to `AsMemory` too: if the pool ever hands back a larger array, the loop still reads chunks of the size the protocol expects. ## Where this bites in practice - `Encoding.UTF8.GetString(buffer)` decodes trailing garbage after the real text. - `stream.Write(buffer)` writes the whole rented length, not the bytes you filled. - `Array.Sort(buffer)` or `buffer.AsSpan().IndexOf(x)` searches data you never wrote. - A test that rents once on a fresh process sees zeros and passes, then fails in production where arrays are reused. ## clearArray and sensitive data Pass `clearArray: true` when the buffer held something another renter must not read: tokens, keys, passwords, another user's payload. For ordinary I/O buffers the cost of clearing usually is not worth it, because a correct caller never reads past its own count. Clearing does not make a buggy caller safe; it only changes what the bug reads.

  • Does a private pool from ArrayPool<T>.Create() round the same way?
    Yes, and it can return even more. `ArrayPool<T>.Create()` uses power-of-two buckets too, by default up to 1024 * 1024 elements and 50 arrays per bucket, and when its own bucket is empty it may hand you an array from the next bucket up. A request above its maximum is allocated at exactly that length and dropped on return.
  • When should Return be called with clearArray: true?
    When the buffer held data another renter must not see, such as tokens, keys, passwords or another user's payload. It clears the whole array before the pool stores it, which costs time proportional to the array length. It does not fix a caller that reads past its own count; it only means that caller reads zeros.
  • What do Rent(0) and Rent(-1) do on the shared pool?
    `Rent(0)` returns the `Array.Empty<T>()` singleton, which `Return` accepts and never stores. `Rent(-1)` throws `ArgumentOutOfRangeException`. Neither allocates a pooled array.

  • Rent(n) returns an array of exactly n elements.
  • Rented arrays come back zeroed, just like new byte[n].
  • buffer.Length tells you how many bytes the last read filled.
  • Return clears the array unless you pass clearArray: false.
  • Asking for more than the pool's biggest bucket throws an exception.

Assumes .NET 10; the Rent contract is long-standing, but the shared pool's bucket sizes and per-thread cache were checked against the .NET 10 source.