-
Notifications
You must be signed in to change notification settings - Fork 4.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Pass number of bytes to Buffer.BlockCopy #33765
Comments
Estimates:
|
If the first argument is an array of a primitive other than Anything other than a simple We can consider an expansion of the |
Usage example: using System;
namespace MyNamespace
{
class Sample
{
public static void Main()
{
int[] src = ...;
int[] dst = ...;
// Warn
Buffer.BlockCopy(src, 0, dst, 0, src.Length);
// Warn
Buffer.BlockCopy(src, 0, dst, 0, dst.Length);
// Warn
int numBytes2 = src.Length;
Buffer.BlockCopy(src, 0, dst, 0, numBytes2);
// Warn
int numBytes3 = dst.Length;
Buffer.BlockCopy(src, 0, dst, 0, numBytes3);
// Do not warn
Buffer.BlockCopy(src, 0, dst, 0, 5);
// Do not warn
int numBytes = ...;
Buffer.BlockCopy(src, 0, dst, 0, numBytes);
// Do not warn
Buffer.BlockCopy(src, 0, dst, 0, GetNumBytes());
// Allowed array data types
byte[] srcByte = ...;
byte[] dstByte = ...;
// Do not warn if underlying array type is byte
Buffer.BlockCopy(srcByte, 0, dstByte, 0, srcByte.Length);
// Do not warn if underlying array type is byte
Buffer.BlockCopy(srcByte, 0, dstByte, 0, dstByte.Length);
sbyte[] srcSbyte = ...;
sbyte[] dstSbyte = ...;
// Do not warn if underlying array type is sbyte
Buffer.BlockCopy(srcSbyte, 0, dstSbyte, 0, srcSbyte.Length);
// Do not warn if underlying array type is sbyte
Buffer.BlockCopy(srcSbyte, 0, dstSbyte, 0, dstSbyte.Length);
}
static int GetNumBytes()
{
return ...;
}
}
}
Question@jeffhandley 's last suggestion to detect if a division is used would not warn anyway because the passed argument would not exactly be |
|
Thanks. The |
Just bringing up a point for clarification. If we had the following code, I don't think the analyzer should be triggered using System;
class Program
{
static void Main()
{
int[] src = new int[] {1, 2, 3, 4};
int[] dst = new int[] {0, 0, 0, 0};
int numOfBytes = src.Length;
SomeFunction(src, dst, numOfBytes);
}
static void SomeFunction(int[] src, int[] dst, int count)
{
Buffer.BlockCopy(src, 0, dst, 0, count); // I don't think it's possbile to know where count is coming from. Looking just at this expression, `count`'s variable declaration will be the parameter in the function definition. I think we should NOT report a diagnostic in this case
}
} |
Closed via dotnet/roslyn-analyzers#5242 |
The
count
argument is in bytes, but it's easy to accidentally do something likeBuffer.BlockCopy(src, 0, dst, 0, src.Length)
, and ifsrc
is an array of elements larger than bytes, this is a bug.Category: Reliability
The text was updated successfully, but these errors were encountered: