Signed word lengths and indexes

"Jérôme M. Berger" jeberger at free.fr
Wed Jun 16 12:46:27 PDT 2010


Jérôme M. Berger wrote:
> Jérôme M. Berger wrote:
>> Walter Bright wrote:
>>> Jérôme M. Berger wrote:
>>>>     Actually, that problem already occurs in C. I've had problems when
>>>> porting code from x86 to x86_64 because some unsigned operations
>>>> don't behave the same way on both...
>>> How so? I thought most 64 bit C compilers were specifically designed to
>>> avoid this problem.
>> 	I can't isolate it to a minimal test case, but at my job, we make
>> an image processing library. Since negative image dimensions don't
>> make sense, we decided to define width and height as "unsigned int".
>> Now, we have code that works fine on 32-bit platforms (x86 and arm)
>> but segfaults on x86_64. Simply adding an (int) cast in front of the
>> image dimensions in a couple of places fixes the issue (tested with
>> various versions of gcc on linux and windows).
>>
> 	Gotcha! See the attached test case. I will post the explanation for
> the issue as a reply to give everyone a chance to try and spot the
> error...
> 
	The problem comes from the fact that an unsigned int is 32 bits,
even on 64 bits architecture, so what happens is:

 - Some operation between signed and unsigned ints gives a negative
result. Because of the automatic type conversion rules, this is
converted to an unsigned 32-bit int;

 - The result is added to a pointer. On 32-bit systems, the
operation simply wraps around and works. On 64-bit systems, the
result is extended to 64 bits by adding zeroes (since it is
unsigned) and the resulting pointer is wrong.

	That's reasonably easy to spot in this simple example. It's a lot
more difficult on real world code. We had the problem because we
were moving a pointer through the image data. As soon as the
movement depended on the image dimensions (say: move left by 1/4 the
width), then the program crashed. Every other kind of move worked
just fine...

		Jerome
-- 
mailto:jeberger at free.fr
http://jeberger.free.fr
Jabber: jeberger at jabber.fr

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 198 bytes
Desc: OpenPGP digital signature
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20100616/47ec78c7/attachment.pgp>


More information about the Digitalmars-d mailing list