473,804 Members | 2,160 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C# Unsafe Bug

JS
I was writing some routines which could do bitwise boolean operations
on byte arrays, and I ran into what I think is a bug with C#'s unsafe
code. I am pasting a console application below. Can anyone give an
explanation, or has this type of problem been reported already?
Thanks.

using System;
using System.Collecti ons.Generic;
using System.Text;

namespace UnsafeBug
{
class Program
{
static void Main(string[] args)
{
byte[] dest = new byte[] { 0x01, 0xff };
byte[] sdata1 = new byte[] { 0x01, 0xff };
UnsafeOr(sdata1 , dest, dest, 7);

for (int ii = 0; ii < dest.Length; ii++)
{
Console.WriteLi ne("Byte {0} = 0x{1:X2}", ii + 1, dest[ii]);
}
Console.WriteLi ne("Hit Enter to quit..."); Console.ReadLin e();
}

// OR's together 2 byte arrays into 'dest' without touching the
first few bits of 'dest'.
// it is allowed for sources/destinations to be the same.
static void UnsafeOr(byte[] src1, byte[] src2, byte[] dest, int
firstBit)
{
byte mask = (byte)(0x80 >> firstBit);
int nbytes = Math.Min(Math.M in(src1.Length, src2.Length),
dest.Length);
unsafe
{
fixed (byte* s1data = &src1[0], s2data = &src2[0], ddata =
&dest[0])
{
byte* s1ptr = s1data;
byte* s2ptr = s2data;
byte* dptr = ddata;

#if false
// this version works
byte val = (byte)(*dptr & ~mask);
*dptr++ = (byte)(val | ((*s1ptr++ | *s2ptr++)&mask) );
#else
// this version does not work
*dptr++ = (byte)((*dptr & ~mask) | ((*s1ptr++ |
*s2ptr++)&mask) );
#endif
for (int ii = 1; ii < nbytes; ii++)
{
*dptr++ = (byte)(*s1ptr++ | *s2ptr++);
}
}
}
}
}
}

Dec 31 '05 #1
12 1812
JS <st********@ic. net> wrote:
I was writing some routines which could do bitwise boolean operations
on byte arrays, and I ran into what I think is a bug with C#'s unsafe
code. I am pasting a console application below. Can anyone give an
explanation, or has this type of problem been reported already?


<snip>

I don't believe this is a bug, and I don't believe it has anything to
do with unsafe code. Here's a smaller app which shows the same effect
without any unsafe code.

using System;

class Test
{
static void Main()
{
int[] x = {10};
int i=0;
x[i++] = i;
Console.WriteLi ne (x[0]);
}
}

That will print out 1, not 0 (which is what you'd have expected, I
believe).

What you're seeing is the postfix increment being executed before the
evaluation of the right hand side of the assignment operator.

This is entirely correct according to the specification.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Dec 31 '05 #2
JS wrote:
I was writing some routines which could do bitwise boolean operations
on byte arrays, and I ran into what I think is a bug with C#'s unsafe
code. I am pasting a console application below. Can anyone give an
explanation, or has this type of problem been reported already?
Thanks.

using System;
using System.Collecti ons.Generic;
using System.Text;

namespace UnsafeBug
{
class Program
{
static void Main(string[] args)
{
byte[] dest = new byte[] { 0x01, 0xff };
byte[] sdata1 = new byte[] { 0x01, 0xff };
UnsafeOr(sdata1 , dest, dest, 7);

for (int ii = 0; ii < dest.Length; ii++)
{
Console.WriteLi ne("Byte {0} = 0x{1:X2}", ii + 1, dest[ii]);
}
Console.WriteLi ne("Hit Enter to quit..."); Console.ReadLin e();
}

// OR's together 2 byte arrays into 'dest' without touching the
first few bits of 'dest'.
// it is allowed for sources/destinations to be the same.
static void UnsafeOr(byte[] src1, byte[] src2, byte[] dest, int
firstBit)
{
byte mask = (byte)(0x80 >> firstBit);
int nbytes = Math.Min(Math.M in(src1.Length, src2.Length),
dest.Length);
unsafe
{
fixed (byte* s1data = &src1[0], s2data = &src2[0], ddata =
&dest[0])
{
byte* s1ptr = s1data;
byte* s2ptr = s2data;
byte* dptr = ddata;

#if false
// this version works
byte val = (byte)(*dptr & ~mask);
*dptr++ = (byte)(val | ((*s1ptr++ | *s2ptr++)&mask) );
#else
// this version does not work
*dptr++ = (byte)((*dptr & ~mask) | ((*s1ptr++ |
*s2ptr++)&mask) );
#endif
for (int ii = 1; ii < nbytes; ii++)
{
*dptr++ = (byte)(*s1ptr++ | *s2ptr++);
}
}
}
}
}
}


The problem lies in the fact that left side of the assignment is
evaluated before the right side. First, *dptr++ is evaluated,
incrementing dptr but still resulting in the correct destination
address. When the right side is evaluated afterwards, the dptr is
already incremented so it points to a different location.

So you can either change your code to

*dptr = (byte)((byte)(* dptr++ & ~mask) | ((*s1ptr++ | *s2ptr++)&mask) );

or (maybe safer)

*dptr = (byte)((byte)(* dptr & ~mask) | ((*s1ptr++ | *s2ptr++)&mask) );
dptr++

HTH,
Stefan
Dec 31 '05 #3
JS
OK, I guess. It was my understanding that postfix was done after the
statement was executed. I suppose I should look at the language
specifications.

Thanks for the quick responses.

Dec 31 '05 #4
JS <st********@ic. net> wrote:
OK, I guess. It was my understanding that postfix was done after the
statement was executed. I suppose I should look at the language
specifications.


Well, while I would never suggest that it's not a good idea to know the
language well, I think it would also be better to split your current
statement up into potentially several, to make it more readable. It
certainly wasn't obvious to me what it should be doing, partly due to
the number of side-effects involved.

I assume the reason for using unsafe code is performance - I would
benchmark various possible versions of the code (including safe code)
and record details of those benchmarks (source and result). You can
then make a trade-off between performance and readability (if, indeed,
the most readable code doesn't also perform the best).

(Also, shouldn't the mask be 0xff >> firstBit, not 0x80 >> firstBit?)

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Dec 31 '05 #5
JS
Yes, it should have been 0xff>>firstBit. It got messed up when I
created the small project to demonstrate my 'problem'.

As you surmised we need to fully optimize this function. Our
applications sometimes call these image processing operations many
times, with images up to 8192x8192. If we don't optimize, it gets very
slow.

I will try benchmarking the performance using safe code, as you
suggest, although for these low-level functions readability is
secondary to speed.

Dec 31 '05 #6
JS
I have done a quick benchmark:

Average time to do simple binary image OR (1000x1000 pixels = 125000
bytes):
Unsafe code: 3.0 milliseconds
Safe code: 2.5 milliseconds

This is significant but not too significant. I will consider having 2
versions of each function, the default function being safe and an
unsafe version where it makes sense.

Dec 31 '05 #7
JS wrote:
I have done a quick benchmark:

Average time to do simple binary image OR (1000x1000 pixels = 125000
bytes):
Unsafe code: 3.0 milliseconds
Safe code: 2.5 milliseconds

This is significant but not too significant. I will consider having 2
versions of each function, the default function being safe and an
unsafe version where it makes sense.

The safe version seems to be faster in this case, so I think there is no
real need to use unsafe code at all ;)
Dec 31 '05 #8
JS <st********@ic. net> wrote:
I have done a quick benchmark:

Average time to do simple binary image OR (1000x1000 pixels = 125000
bytes):
Unsafe code: 3.0 milliseconds
Safe code: 2.5 milliseconds

This is significant but not too significant. I will consider having 2
versions of each function, the default function being safe and an
unsafe version where it makes sense.


Have you got those the wrong way round? If the safe code is faster, why
not use that all the time?

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Dec 31 '05 #9
JS
Sorry, Safe=3ms Unsafe=2.5ms

Dec 31 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1917
by: Elidel | last post by:
Is the use of a COM object in a c# program considered 'unsafe' code ? Does the method that calls the COM object need the 'unsafe' keyword ? Is code that calls a COM object considered unmanaged? Is 'unsafe' code the same as unmanaged code ?
3
3151
by: Andre | last post by:
if I have an unsafe method that takes in two arrays, performs some operations and returns; I know that the garbage collector will not collect objects allocated inside the unsafe method. However, if I'm calling this method from a main() method of a class which is safe (i.e managed), will the allocated array (which, suppose, has been allocated inside the main() method) be collected by the garbage collector after it's been used? Also, how do...
8
5465
by: | last post by:
Wel, I am rebuilding the VC# 2002 project that I have deployment problems with the 2003 version, hoping this solves the problems, but now I encounter this wierd bug??? If I have the project, and do not compile with "Allow Unsafe Code Blocks=false" set to true, then the project compiles and no problems. BUT if I compile with "Allow Unsafe Code Blocks=true" then I het the error below. With unsafe {} of unsave{} removed it dos not solve the...
4
609
by: Jon Milner | last post by:
How do I declare that my code is unsafe? Sorry the help files at my University have not been installed!
17
1877
by: Bradley1234 | last post by:
Sorry if this is obvious, but Ill ask... Is there a new way of using pointer operations in C# ? Ive got a Deitel book on C# that neither mentions the word "pointer" nor "unsafe" in the index. coming from a C/C++ world, pointers make perfect sense, and getting up to speed on CS, did pointers go away?
4
4319
by: CodeTyro | last post by:
My native language being C++, I've got a few questions that a couple of hours of searching on msdn didn't answer. First, when using unsafe code and pointers, what is the C# equivalent to the C++ "delete" command? I would like to keep my memoryspace clean, but I've been unable to find a way to do it thus far. Second, I'm using structs to store a specific set of data. Is there a C# equivalent to the C++ STL "Vector" (or any of the...
1
1643
by: Z | last post by:
Hello, In my C# program I have a function that uses pointers. Is there a way to tell the compiler to compile only this function with the unsafe switch and compile the remaining project as safe code? I enclosed the body of the function in unsafe block like this: public static void Foo() { unsafe
2
3395
by: NickP | last post by:
Hi there, I am currently moving my API declarations into relevant classes for Safe and Unsafe methods. My understanding is that unsafe methods are ones that require elevated security priviledges in order to perform their function. Is there a reference available as to what methods are safe and which unsafe? For example I cam currently looking at the method SHGetFileInfo, I presume this is unsafe as you would need to have priviledges in...
0
1255
by: =?Utf-8?B?U2hhcm9u?= | last post by:
I have two piece of unsafe code. In the first one I'm getting the byte* pointer of a Bitmap data, and the second one in inside a loop that uses that byte* pointer to set the data in the Bitmap. The trouble is that that each of this pieces of code are bound by a different unsafe section, therefore I'm getting an error that the second unsafe section does not "The name 'refBuf' does not exist in the current context" ...
2
1943
by: wmhnq | last post by:
private void button1_Click(object sender, EventArgs e) { unsafe { string str = "abcde"; fixed (char* pStr = str) { A a = new A(pStr); a.change(); MessageBox.Show(str.ToString());
0
9711
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10595
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10343
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10335
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9169
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7633
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5668
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3831
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3001
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.