0 day streak
javascript / intermediate
Snippet

Defensive Coding with Secure Buffer Allocation

Buffer.alloc(size) initializes memory with zeros, preventing sensitive data 'leaks' from previously used memory. While allocUnsafe is faster, it should only be used if the buffer is immediately and completely overwritten.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
const sensitiveData = "password123";
// SAFE: Zero-fills the memory
const secureBuffer = Buffer.alloc(16);
secureBuffer.write(sensitiveData);
// UNSAFE: May contain old, sensitive data from memory
const unsafeBuffer = Buffer.allocUnsafe(16);
console.log('Secure:', secureBuffer);
console.log('Unsafe (raw):', unsafeBuffer);
nodejs
Breakdown
1
Buffer.alloc(16)
Allocates 16 bytes of memory and fills it with zeros.
2
Buffer.allocUnsafe(16)
Allocates memory without clearing it, potentially exposing old data.
3
secureBuffer.write(...)
Safely writes the string into the zeroed memory.