What is the Buffer.allocUnsafeSlow() method in Node.js?
The Buffer.allocUnsafeSlow(size) method in Node.js creates a new Buffer of size bytes. It does not initialize the memory backing up the buffer array with zeros. It is an unsafe method to use since it can cause memory leaks of potentially sensitive data.
Therefore, it is always good to call the buffer.fill(0) method on the newly allocated buffer to zero out the underlying buffer array and prevent any memory leaks.
Syntax
Static method: Buffer.allocUnsafe(size)
Parameters
size: Thesizeis an integer that represents the length of the new buffer in bytes.
If the size is , then a zero-sized buffer is allocated. The size must be between 0 and buffer.constants.MAX_LENGTH.
Return value
Buffer.allocUnsafeSlow() returns a new buffer object of length size bytes.
Exceptions
Buffer.allocUnsafeSlow() throws an ERR_INVALID_ARG_VALUE exception if the value of size is greater than buffer.constants.MAX_LENGTH or less than zero.
Code
const buf = Buffer.allocUnsafeSlow(10);console.log("Uninitialized memeory (Unsafe):", buf)buf.fill(0);console.log("Manually zeroed out memory: (Safer)", buf)
Explanation
In the code above, we create a buffer object named buf using the Buffer.allocUnsafeSlow() method.
On line 2, we print out
the contents of the underlying memory. Notice that the underlying memory contains garbage values. This is because the Buffer.allocUnsafeSlow() does not initialize the memory.
This can be used for malicious purposes because it allows us to read contents of memory that might contain sensitive data from previous processes.