Static array initialisation
Ali Çehreli
acehreli at yahoo.com
Thu Apr 1 10:09:27 UTC 2021
On 4/1/21 2:30 AM, DLearner wrote:
> immutable uint MemSize=100; // Memory size in bytes.
> ubyte[MemSize] MemPool = 8; // Initialised to 8 for debugging.
Valid index values there are from 0 to 99, inclusive.
> WkPtr = &MemPool[0];
>
> counter = 1;
> while (counter <= 102) {
>
> idx = counter - 1;
So, idx will have the incorrect values of 100 and 101.
> WkUbyte = *(WkPtr + idx);
That's undefined behavior. We can talk about variable placement on the
stack, padding, alignment, etc. but we cannot attempt to prove how much
memory is allocated for ubyte[100] by using undefined behavior like that
code.
We can have a ubyte[100] as a member of a struct and then look at the
bytes of an instance of that struct but we can't walk over the bytes of
the function call stack randomly. I mean, we can, but the observations
may not make sense.
Ali
P.S. MemPool.sizeof is the amount of memory used for ubyte[100]. Here is
proof:
void main() {
alias T = ubyte[100];
T[2] arr;
assert(arr.sizeof == 2 * T.sizeof); // Passes
}
As you can see, there is nothing other than 100 bytes used for
ubyte[100]. (The results may be different for different types due to
alignment requirements.)
More information about the Digitalmars-d-learn
mailing list