Sunday, June 17, 2007

My 64-bit porting experiences -V

5. Use of compatible, but incorrect datatypes

An API function, ‘func1’ returns int*, which actually points to an array of two integers. The part of code that uses this function is as follows:

long *lp = func1(…);
int lval = lp[0];
int rval = lp[1];

The results were correct in 32-bit, because int and long are same size. On 64-bit, the return values were incorrect, because of the difference in size of int and long. ‘lp[0]’ represents a 64-bit value, which contains both the int values that are returned by ‘func1’. When it is assigned to ‘lval’, the lower 32 bits are assigned to ‘lval’, which was the value that needed to be assigned to ‘rval’. ‘lp[1]’ reads next 64 bits from memory and assigns the lower 32 bits of it to ‘rval’. So, ‘lval’ gets incorrect value, while ‘rval’ gets junk.

6 comments:

Rajnish Gupta said...

Isn't this statement wrong :-)?
"An API function, ‘func1’ returns int*,"

Sigma said...

@Rajnish: Thanks for your visit here :-). I am not able to access your profile. Could you please enable your profile so that it can be viewed by other users, or leave a link of your blog.

Why do you say that the statment is wrong? I didn't quite understand it. Or perhaps, I didn't explain something well enough. What I intended to say was that the return type of this function, 'func1' was an int*, and it actually returned an array of two integers (since a pointer can very well represent an array).

Rajnish Gupta said...

Return type mentioned in the example is not int*, it is long *. See below
long *lp = func1(…);

Sigma said...

Oh .... I see.
This is not the declaration of the function - this is the incorrect usage that I want to point out :-)

Rajnish Gupta said...

You didn't get the warning at the compile time?

BTW I have created my profile and my first post tooo :-)

Sigma said...

Since when do software programmers heed warnings ? ;-)
So, frankly, I dont know :-))