Segfault with std.container.Array but not regular dynamic array

Maxim Fomin maxim at maxim-fomin.ru
Tue Nov 27 10:04:18 PST 2012


On Monday, 26 November 2012 at 22:42:53 UTC, Dan wrote:
> On Monday, 26 November 2012 at 19:14:09 UTC, Joseph Rushton 
> Wakeling wrote:
>> On 11/26/2012 04:07 PM, Joseph Rushton Wakeling wrote:
>
> Ok, now I really want to know why it crashes. I've narrowed it 
> down to an example below. It seems there is a problem with 
> RefCounted being used as value in a map.
>
> <skipped rest>

I think it crashes because of using associative array. Assignment 
to an absent aa member causes memory allocation without proper 
object construction, and immediately after compiler issues call 
to opAssign for not-constructed object - that is why "this" 
pointer is "bogus" on entering function.

import std.stdio;

struct S
{
     int i = 42;
     struct SS
     {
         int ii = 41;
         this(this) { writeln("SS postblit"); }
         void opAssign(SS rhs) { writeln("SS opAssign"); }
     }
     SS ss;
     this(this) { writeln("S postblit"); }
     void opAssign(S rhs)
     {
         writeln("S opAssign");
     }
     ~this()
     {
         writefln("i=%d, ii=%d", i, ss.ii);
     }
}

S[int] map ;
// S[2] map;
// S[] map = [S(), S()];

void main()
{
     map[1] = S();
}

AA version on windows 2.060 prints

SS postblit
S opAssign
i=42, ii=41
i=4269990, ii=4269984 //garbage

Switching to dynamic or static array fixes the program.


More information about the Digitalmars-d-learn mailing list