diff --git a/lib/buffer.js b/lib/buffer.js index c75dbc93a8a..000c54b3a88 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -339,6 +339,9 @@ Buffer.prototype.write = function(string, offset, length, encoding) { } encoding = String(encoding || 'utf8').toLowerCase(); + if (string.length > 0 && (length < 0 || offset < 0)) + throw new RangeError('attempt to write beyond buffer bounds'); + var ret; switch (encoding) { case 'hex': diff --git a/test/simple/test-buffer.js b/test/simple/test-buffer.js index 3808442ad19..0d071127c93 100644 --- a/test/simple/test-buffer.js +++ b/test/simple/test-buffer.js @@ -221,6 +221,16 @@ new Buffer(0); b.write('', 1024); b.write('', 2048); +// throw when writing past bounds from the pool +assert.throws(function() { + b.write('a', 2048); +}, RangeError); + +// throw when writing to negative offset +assert.throws(function() { + b.write('a', -1); +}, RangeError); + // try to copy 0 bytes worth of data into an empty buffer b.copy(new Buffer(0), 0, 0, 0);