Memory allocation in D (noob question)

Regan Heath regan at netmail.co.nz
Wed Dec 5 03:22:18 PST 2007


Steven Schveighoffer wrote:
> import std.stdio;
> 
> struct X
> {
>         char[5] myArray;
>         int x;
> }
> 
> void main()
> {
>         X[] x = new X[2];
>         x[0].myArray[] = "hello";
>         char[] myslice = x[0].myArray[0..3];
>         writefln("%x %x %x", &x[0].x, &x[0].myArray[0], &myslice[0]);
>         myslice ~= "hithere";
>         writefln("%x %x %x", &x[0].x, &x[0].myArray[0], &myslice[0]);
>         writefln("%s %d", x[0].myArray, x[0].x);
> }
> 
> output:
> 
> 868FE8 868FE0 868FE0
> 868FE8 868FE0 868FE0
> helhi 25970

This one worries me.

I believe the problem is caused by the memory address of myArray[0] 
being the same as the memory address of the struct.  Is this what you 
realised Sean... I may be a bit slow on the uptake here :)

When the slice needs to reallocate the GC checks this address and finds 
enough space following the struct (or perhaps it has allocated on a 
power of two boundary and already has enough) and it allows the 
concatenation to write to that memory.

The problem is that it doesn't realise the memory was allocated to a 
struct, and is being reallocated by an array slice.  So, the array 
concatenation overwrites the memory occupied by the int 'x'.

Ick.

I would have expected a static array to be un-reallocatable, so any 
concatenation performed on a slice of one to cause a copy to be made. 
But of course all that information is lost at the place where the 
reallocation is done, it's simply a memory address with a certain amount 
of memory associated with it.

R



More information about the Digitalmars-d mailing list