How the memory layout of global variable is reliable ?

Cjkp via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Oct 23 00:55:36 PDT 2014


On Wednesday, 22 October 2014 at 20:37:43 UTC, Freddy wrote:
> On Wednesday, 22 October 2014 at 20:29:58 UTC, Cjkp wrote:
>> Hello, I have an idea about a small code tool related to the 
>> application resources.
>> It would rely on the assumption that some global variabled, 
>> sharing the same type and attributes, declared in group, are 
>> contiguous.
>>
>> In short I need to know if the following assertions are always 
>> true and reliable over time:
>>
>> --------------
>> import std.stdio;
>>
>> // used as base adress
>> static string beg = "";
>> // arbitrary generated by a tool and mixed at compile time.
>> static string a = "";
>> static string b = "";
>> static string c = "";
>> static string d = "";
>> static string e = "";
>> static string f = "";
>>
>> void main(string args[])
>> {
>>    void* offs = &beg;
>>    assert( &a == (offs + (size_t.sizeof * 2) * 1) ); // length 
>> + ptr
>>    assert( &b == (offs + (size_t.sizeof * 2) * 2) ); // length 
>> + ptr
>>    assert( &c == (offs + (size_t.sizeof * 2) * 3) ); // etc.
>>    assert( &d == (offs + (size_t.sizeof * 2) * 4) );
>> }
>> --------------
>>
>> In a second time I need to be sure that the return tuple of 
>> the trait "allMembers" follow the declarations order. The 
>> documentation says that:
>>
>> "The order in which the strings appear in the result is not 
>> defined".
>>
>> But so far, it looks like it's ordered according to the 
>> declaration (at least for a module containing only some global 
>> variables).
>>
>> Any other remarks about the topic are welcome.
>
> Plese don't do this, it's undefined behavior and could make you
> code invalid with a new compiler release or different compiler.
> If possible use static arrays instead.
> ----
> int[2] arr=[1,2];
> @property auto ref b(){
>      return arr[1];
> }
> ---

I've probably badly explained the what and the why. I ask this 
because of this draft: http://dpaste.dzfl.pl/e15305cbc32d

Tool: generate a module with some static strings. (used as 
ressources, e.g pictures, tables, etc.)
Manager: use the first item as base address since the other are 
using the import expression.

Actually I don't get the sample you added to your answer, that 
leads me to think that my initial Question is not well exposed.



More information about the Digitalmars-d-learn mailing list