Buffer.alloc() and Buffer.allocUnsafe()
The two ways to create a new Buffer of a given size: alloc() fills it with zeros, while allocUnsafe() skips that step and may contain old data.
Sending or logging an allocUnsafe buffer before every byte is overwritten can leak passwords or keys from earlier memory.
In more detail
allocUnsafe() is faster, but its bytes may be left over from memory used earlier, including secrets. Use it only when you overwrite every byte immediately, and use alloc() everywhere else.
Related terms
- Buffer — A Node.js object holding a fixed-length run of raw bytes stored outside the V8 heap; more generally, any memory that holds data on its way somewhere.
- uninitialized memory — Memory handed to a program without being cleared first, so it still contains whatever data was there before.
- slab allocator — A memory manager that reserves one large block up front and hands out small pieces of it, avoiding many tiny allocations.
Taught in
- Node.js Process Architecture: Memory & Heap Spaces — Node.js Internals & Backend Services
- Buffer Fundamentals: Slab Allocator & V8 Memory — Node.js Internals & Backend Services