Our website uses cookies to enhance your browsing experience.
Accept
to the top
close form

Fill out the form in 2 simple steps below:

Your contact information:

Step 1
Congratulations! This is your promo code!

Desired license type:

Step 2
Team license
Enterprise license
** By clicking this button you agree to our Privacy Policy statement
close form
Request our prices
New License
License Renewal
--Select currency--
USD
EUR
* By clicking this button you agree to our Privacy Policy statement

close form
Free PVS‑Studio license for Microsoft MVP specialists
* By clicking this button you agree to our Privacy Policy statement

close form
To get the licence for your open-source project, please fill out this form
* By clicking this button you agree to our Privacy Policy statement

close form
I am interested to try it on the platforms:
* By clicking this button you agree to our Privacy Policy statement

close form
check circle
Message submitted.

Your message has been sent. We will email you at


If you do not see the email in your inbox, please check if it is filtered to one of the following folders:

  • Promotion
  • Updates
  • Spam

>
>
>
Why A + B != A - (-B)

Why A + B != A - (-B)

Dec 21 2009
Author:

While developing Viva64 analyzer intended for detecting 64-bit errors, I sometimes encounter interesting ways of code behavior. I would like to show you one example that is not very interesting practically but might be helpful in understanding more complicated cases.

char *A = "123456789";
unsigned B = 1;
char *X = A + B; // X: "23456789"
char *Y = A - (-B); // Y: <Bad Ptr>

If we compile the 32-bit version of the code, the expressions "A + B" and "A - (-B)" will be equivalent. In the 32-bit code, the pointers X and Y point to the second item of the array A. To understand it better look at the Figure 1 showing the process of calculating "A - (-B)".

0039_Why_A_+_B_!=_A_-_(-B)/image1.png

But when we compile the 64-bit code, the expressions "A + B" and "A - (-B)" mean absolutely different things. The subexpression "-B" has an unsigned type and equals 0xFFFFFFFFu. And it is this value 0xFFFFFFFFu that is subtracted from the pointer (see Figure 2).

0039_Why_A_+_B_!=_A_-_(-B)/image2.png

The shown error leads to an access outside the array on a 64-bit system. Such errors might occur when working with negative indexes when 32-bit unsigned variables are used to store them. Here is an example:

unsigned Index = -1;
Array[Index] = Z;

Like in the previous case, the expression "Array[Index] = Z;" works well in the 32-bit program but leads to an error in the 64-bit one.

Conclusion:

You should avoid using unsigned data types to store negative values. If the variables used to access array items can take negative values, use only signed data types, for example "int". Or rather use the types size_t and ptrdfiff_t.

Popular related articles


Comments (0)

Next comments next comments
close comment form