{"record":{"id":"97935ac574639005","repo":"SixLabors/ImageSharp","slug":"attempted-to-allocate-a-buffer-of-negative-length-length","errorCode":null,"errorMessage":"Attempted to allocate a buffer of negative length={length}.","messagePattern":"Attempted to allocate a buffer of negative length=(.+?)\\.","errorType":"exception","errorClass":"InvalidMemoryOperationException","httpStatus":null,"severity":"critical","filePath":"src/ImageSharp/Memory/InvalidMemoryOperationException.cs","lineNumber":32,"sourceCode":"    /// <summary>\n    /// Initializes a new instance of the <see cref=\"InvalidMemoryOperationException\"/> class.\n    /// </summary>\n    /// <param name=\"message\">The exception message text.</param>\n    public InvalidMemoryOperationException(string message)\n        : base(message)\n    {\n    }\n\n    /// <summary>\n    /// Initializes a new instance of the <see cref=\"InvalidMemoryOperationException\"/> class.\n    /// </summary>\n    public InvalidMemoryOperationException()\n    {\n    }\n\n    [DoesNotReturn]\n    internal static void ThrowNegativeAllocationException(long length) =>\n        throw new InvalidMemoryOperationException($\"Attempted to allocate a buffer of negative length={length}.\");\n\n    [DoesNotReturn]\n    internal static void ThrowInvalidAlignmentException(long alignment) =>\n        throw new InvalidMemoryOperationException(\n                $\"The buffer capacity of the provided MemoryAllocator is insufficient for the requested buffer alignment: {alignment}.\");\n\n    [DoesNotReturn]\n    internal static void ThrowAllocationOverLimitException(ulong length, long limit) =>\n            throw new InvalidMemoryOperationException($\"Attempted to allocate a buffer of length={length} that exceeded the limit {limit}.\");\n\n    [DoesNotReturn]\n    internal static void ThrowAccumulativeAllocationOverLimitException(long requestedLength, long totalLength, long limit) =>\n            throw new InvalidMemoryOperationException(\n                $\"Attempted to allocate a buffer of length={requestedLength} that would increase the accumulative allocation size to {totalLength}, exceeding the limit {limit}.\");\n}\n","sourceCodeStart":14,"sourceCodeEnd":48,"githubUrl":"https://github.com/SixLabors/ImageSharp/blob/59ce6af6fc29027cda277ef62d4d1694a8acce91/src/ImageSharp/Memory/InvalidMemoryOperationException.cs#L14-L48","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","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."],"exampleFix":"// before\nvar buffer = allocator.Allocate<Rgba32>(width * height);\n// after\nlong pixelCount = (long)width * height;\nif (pixelCount < 0) throw new InvalidImageContentException(\"Corrupt dimensions\");\nvar buffer = allocator.Allocate<Rgba32>((int)pixelCount);","handlingStrategy":"validation","validationCode":"if (length < 0)\n    throw new InvalidImageContentException($\"Computed buffer length {length} is negative; input is corrupt.\");\nvar buffer = allocator.Allocate<T>(length);","typeGuard":null,"tryCatchPattern":"try { using var buf = allocator.Allocate<T>(length); }\ncatch (InvalidMemoryOperationException ex) when (ex.Message.Contains(\"negative\")) { /* treat input as corrupt */ }","preventionTips":["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."],"tags":["memory","allocation","csharp","corrupt-input"],"backgroundTag":"value-out-of-range","analyzedSha":"59ce6af6fc29027cda277ef62d4d1694a8acce91","analyzedAt":"2026-09-13T18:34:59.331Z","contentChangedAt":"2026-09-13T18:34:59.331Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}