How the memory layout of global variable is reliable ?
Freddy via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Oct 22 13:37:43 PDT 2014
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];
}
---
More information about the Digitalmars-d-learn
mailing list