nissl-lab / npoi

a .NET library that can read/write Office formats without Microsoft Office installed. No COM+, no interop.
Apache License 2.0
5.74k stars 1.43k forks source link

ByteArrayOutputStream is not disposed in NPOI.Util.IOUtils.ToByteArray method. Potential Memory leak #1388

Closed guangyu2002 closed 1 month ago

guangyu2002 commented 4 months ago

NPOI Version

2.7.1-rc1

File Type

Issue Description

///

/// Reads up to {@code length} bytes from the input stream, and returns the bytes read. /// /// /// /// public static byte[] ToByteArray(Stream stream, int length) { ByteArrayOutputStream baos = new ByteArrayOutputStream(length == Int32.MaxValue ? 4096 : length);

        byte[] buffer = new byte[4096];
        int totalBytes = 0, readBytes;
        do
        {
            readBytes = stream.Read(buffer, 0, Math.Min(buffer.Length, length - totalBytes));
            totalBytes += Math.Max(readBytes, 0);
            if (readBytes > 0)
            {
                baos.Write(buffer, 0, readBytes);
            }
        } while (totalBytes < length && readBytes > 0);

        if (length != Int32.MaxValue && totalBytes < length)
        {
            throw new IOException("unexpected EOF");
        }

        return baos.ToByteArray();
    }
tonyqus commented 4 months ago

Yes, it can be an issue. Can you create a PR for this?

guangyu2002 commented 4 months ago

Yes, it can be an issue. Can you create a PR for this?

Of course, I'll create a PR for this issue as soon as possible.