SixLabors/ImageSharp · critical · InvalidMemoryOperationException
Attempted to allocate a buffer of negative length=
Error message
Attempted to allocate a buffer of negative length={length}. What it means
ImageSharp's memory allocator detected a request to allocate an IMemoryOwner<T> buffer with a negative length. Negative lengths cannot come from valid image data, so the library fails fast via ThrowNegativeAllocationException instead of corrupting memory or throwing confusing downstream errors.
Solutions
- Validate the source image: try opening it with a fresh Image.Identify/load and check for InvalidImageContentException; if corrupt, the file is the problem.
- Audit the length computation that reached Allocate and guard it: reject negative sizes before calling the allocator.
- If dimensions come from untrusted input, clamp them to sane maxima (e.g. < 100M pixels) before allocation.
Example fix
// before
var buffer = allocator.Allocate<Rgba32>(width * height);
// after
long pixelCount = (long)width * height;
if (pixelCount < 0) throw new InvalidImageContentException("Corrupt dimensions");
var buffer = allocator.Allocate<Rgba32>((int)pixelCount); Defensive patterns
Strategy: validation
Validate before calling
if (length < 0)
throw new InvalidImageContentException($"Computed buffer length {length} is negative; input is corrupt.");
var buffer = allocator.Allocate<T>(length); Try / catch
try { using var buf = allocator.Allocate<T>(length); }
catch (InvalidMemoryOperationException ex) when (ex.Message.Contains("negative")) { /* treat input as corrupt */ } Prevention
- Validate image dimensions from headers before allocating (positive, within sane maxima).
- Use checked arithmetic or long intermediates for width*height products to avoid overflow-derived negatives.
- Never feed unvalidated user input directly into allocation sizes.
When it happens
Trigger: Any MemoryAllocator.Allocate<T>(length) path (directly or via buffer pools / MemoryGroup allocation) where the computed length parameter is negative — typically length was derived from a header field or width*height calculation that overflowed or was read from corrupt data.
Common situations: Decoding malformed/corrupt images where header dimensions or offsets are attacker-controlled or damaged; integer arithmetic bugs in custom codecs; passing unvalidated user input as a buffer size.
Understand the failure class
Background: "value must be between 0 and 1" / "out of range" / "must not be negative" errors: fixing range-validation failures across open-source libraries — this error's family across 42 libraries.
Related errors
- Column regions should not overlap!
- DangerousGetRowSpan( ). Y was out of range. Height=
- Trying to copy/swap incompatible buffers. This is most…
- Wrap: buffers should be uniformly sized!
- Wrap: the last buffer is too large!
AI-assisted analysis of SixLabors/ImageSharp@59ce6af6fc (2026-09-13).
Data as JSON: /api/errors/97935ac574639005.
Report an issue: GitHub.
Appendix: source
Thrown at src/ImageSharp/Memory/InvalidMemoryOperationException.cs:32
/// <summary>
/// Initializes a new instance of the <see cref="InvalidMemoryOperationException"/> class.
/// </summary>
/// <param name="message">The exception message text.</param>
public InvalidMemoryOperationException(string message)
: base(message)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="InvalidMemoryOperationException"/> class.
/// </summary>
public InvalidMemoryOperationException()
{
}
[DoesNotReturn]
internal static void ThrowNegativeAllocationException(long length) =>
throw new InvalidMemoryOperationException($"Attempted to allocate a buffer of negative length={length}.");
[DoesNotReturn]
internal static void ThrowInvalidAlignmentException(long alignment) =>
throw new InvalidMemoryOperationException(
$"The buffer capacity of the provided MemoryAllocator is insufficient for the requested buffer alignment: {alignment}.");
[DoesNotReturn]
internal static void ThrowAllocationOverLimitException(ulong length, long limit) =>
throw new InvalidMemoryOperationException($"Attempted to allocate a buffer of length={length} that exceeded the limit {limit}.");
[DoesNotReturn]
internal static void ThrowAccumulativeAllocationOverLimitException(long requestedLength, long totalLength, long limit) =>
throw new InvalidMemoryOperationException(
$"Attempted to allocate a buffer of length={requestedLength} that would increase the accumulative allocation size to {totalLength}, exceeding the limit {limit}.");
}
View on GitHub (pinned to 59ce6af6fc)