Buffer.alloc Zero-Fills, allocUnsafe Does Not
Buffer.alloc zero-fills every byte while allocUnsafe reuses pooled memory, so uninitialized bytes must be overwritten before leaving your code.
Code
// Buffer.alloc zero-fills every byte, so stale memory from a
// previous write can never leak into what you hand to crypto, the
// network, or a response body
const safe = Buffer.alloc(4);
console.log('alloc: ', [...safe]);
// Buffer.allocUnsafe skips the zero-fill for speed. Its bytes hold
// whatever the shared pool last wrote there — every byte must be
// overwritten before the buffer leaves your code
const fast = Buffer.allocUnsafe(4);
fast.writeUInt32LE(0x12345678);
console.log('allocUnsafe: ', [...fast]);
// Same length, same type — only the initial contents differ
console.log('lengths: ', safe.length, fast.length);
console.log('filled?', fast.readUInt32LE(0) === 0x12345678);Output
Captured from a sandboxed run of this snippet in the build pipeline.
alloc: [ 0, 0, 0, 0 ]
allocUnsafe: [ 120, 86, 52, 18 ]
lengths: 4 4
filled? trueTwo allocations, two guarantees
Buffer.alloc(4) zero-fills: the printed alloc: [ 0, 0, 0, 0 ] shows all four bytes at 0, so stale pool memory can never ride along into crypto, the network, or a response body. Buffer.allocUnsafe(4) skips that fill for speed, and its bytes hold whatever the shared internal pool last wrote there — which is why the example immediately overwrites them with fast.writeUInt32LE(0x12345678) before the buffer leaves the code.
What the run shows
alloc: [ 0, 0, 0, 0 ]
allocUnsafe: [ 120, 86, 52, 18 ]
lengths: 4 4
filled? true
The allocUnsafe numbers are that run’s pool contents, not a stable value — a rerun can print different bytes there until the write lands. The last two lines confirm what both allocations share (lengths: 4 4) and that the explicit write took effect: filled? true comes from fast.readUInt32LE(0) === 0x12345678.
The line that documents the danger
const fast = Buffer.allocUnsafe(4);
fast.writeUInt32LE(0x12345678);
0x12345678 written little-endian lands as bytes 0x78 0x56 0x34 0x12 — decimal [ 120, 86, 52, 18 ], exactly what the console shows — proving the overwrite, not zero-fill, defined those bytes.
Interactive Tools for This Topic
FAQ
- Does this work in a bare project with no dependencies file?
- Yes — a bare project runs it as-is, since nothing needs declaring. Its state lives in module-level bindings: `safe`, `fast`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.