0 day streak
javascript / expert
Snippet

High-Performance Buffer Allocation with allocUnsafe

In Node.js, `Buffer.allocUnsafe` allocates memory without zero-filling it. This is much faster but poses a security risk because the buffer might contain sensitive data from previous allocations. It should only be used if you immediately overwrite the entire buffer with new data.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
const { Buffer } = require('buffer');
// Fast but potentially contains sensitive old data
const fastBuffer = Buffer.allocUnsafe(1024);
// Secure but slower as it zeroes the memory
const secureBuffer = Buffer.alloc(1024);
// Manually clear to reuse safely
fastBuffer.fill(0);
nodejs
Breakdown
1
Buffer.allocUnsafe(1024)
Allocates 1KB of raw memory without initialization.
2
fastBuffer.fill(0)
Manually zeroes the buffer to prevent data leakage before use.