Matt
Matt

Reputation: 629

Unexpected Integer Wrapping

I am having an issue with an integer wrapping around to its minimum value unexpectedly.

The value of the integer is 15 before it wraps to -858993460.

Here is the code that is causing this issue:

while(ArrayLocation2 < EmpArray2Size)
{
    GivenEmployees[(*EmployeeSize++)] = curr2;

    prev2 = curr2;
    if(ArrayLocation2 < EmpArray2Size)
    {
        curr1 = EmpArray2[ArrayLocation2];
    }
    ArrayLocation2++;

    if((ArrayLocation2 >= EmpArray2Size) || (prev2.HourlyRate > curr2.HourlyRate))
    {
        subFiles++;
    }
}

If I manually change the values that it needs (16, 17, 18, etc) it works as expected.

Size is declared as int Size = 21; and passed into its current method as &Size if it makes a difference.

Why is this exactly happening?

Upvotes: 1

Views: 174

Answers (3)

CygnusX1
CygnusX1

Reputation: 21818

GivenEmployees[(*EmployeeSize++)]

Smells like trouble. It is parsed as

GivenEmployees[(*(EmployeeSize++))]

Postfix incrementation has higher precedence than dereferencing. So, you increment a pointer and then dereference it. Is 'EmployeeSize' a pointer to an array?

Upvotes: 1

geekosaur
geekosaur

Reputation: 61449

The expression *EmployeeSize++ returns the value pointed to by EmployeeSize and then increments the pointer, not the pointed-to item. Try (*EmployeeSize)++.

Upvotes: 2

Jonathan Leffler
Jonathan Leffler

Reputation: 754590

The problem is that you are incrementing the pointer - and it ends up pointing into random territory.

You probably intended to write:

GivenEmployees[(*EmployeeSize)++] = cur2;

The parentheses are necessary here; they are unnecessary in the original.


From the comments:

The integer that is wrapping is "EmployeeSize" and is declared as I've described in the OP.

(Except that it is called 'Size' in the original OP.) However, it appears to be:

void this_function(..., int *EmployeeSize, ...)
{
    ...code...
}

Upvotes: 3

Related Questions