Obtaining aligned addresses and aligned spaces for objects

Ali Çehreli acehreli at yahoo.com
Wed Jun 29 11:35:51 PDT 2011


On Wed, 29 Jun 2011 13:43:51 -0400, Steven Schveighoffer wrote:

>> You also say a block is 16 bytes below but the following program seems
>> to be able to put objects at 24 byte intervals.
> 
> Yes, it depends on the contents of the class.  All I was saying is that
> the GC already aligns all blocks to 16-byte boundaries, so the language
> simply doesn't worry about class alignment and padding.

Right. I was preoccupied with the padded space of objects that I misread 
what you said. :)

> Note that your test is not very taxing on alignment -- char does not
> need to be aligned.  I would test with reals and also try and test the
> hidden elements of classes -- the vtable (i.e. virtual functions),
> interfaces, and the monitor object (i.e. try using synchronized) to
> ensure everything is working right.
> 
> Note that having data be misaligned may not result in failure, it may
> just result in slower execution.

Related to that and if I remember correctly, in older hardware accessing 
an int through an odd address value used to be a failure. I think it was 
rejected by the  CPU. Doesn't seem to be the case on my current system. 
No complaints:

import std.stdio;
import std.conv;

void main()
{
    enum offset = 1;
    ubyte[int.sizeof + offset] chunk;

    int * p = cast(int*)(chunk.ptr + offset);
    *p = 0x12345678;

    foreach (b; chunk) {
        writef("%02x ", b);
    }
    writeln();

    assert(*p == 0x12345678);
}

The output:

00 78 56 34 12 

> Also note that you must manually destroy these classes via clear -- the
> GC only destroys the block, and assumes one class instance per block. 
> And in fact, you are not setting the finalize flag on the block on
> creation, so it wouldn't call any destructors.
> 
> -Steve

Thank you very much for all the heads up. Luckily we don't need to deal 
with these issues in daily programming.

Ali


More information about the Digitalmars-d-learn mailing list