On Monday, 26 November 2012 at 15:44:42 UTC, Joseph Rushton Wakeling wrote:
Hello all,

I'm writing some code which is meant to represent a network of linked nodes.
[snip]

Ok, another follow up. I can reproduce your segfault using your posted code, it is included below. But the interesting thing is, I was doing the "testing" out of your Network!Node2 in a unittest section. By whittling down, the smallest crash case I could come up with is this:

import std.typecons;
import std.stdio;
alias RefCounted!(int) Foo;
unittest {
  Foo[int] map;
  map[1] = Foo();
}

When I change that unittest block to a 'void main()' it works just fine. I tried the same change of unittest to 'void main()' on your code and found the same results - no crash. I think the crash issue might not be with map (even though Maxim found some troubling stuff with uninitialized structs being destructed when inserting a key that is not present). Or maybe it is just a map problem and by switching to main I am just getting lucky in not getting a crash.

It would be interesting to know if Joseph was doing his "testing" out in unittest or in a main.

Thanks
Dan

Here is the code that crashes. Change unittest to 'void main()' and it works??

-------------------
import std.container;
import std.stdio;

struct Link {
  int id;
  this(int i) { id=i; }
}

struct Node1
{
  uint id;
  Link[] links;

  this(uint id)
  {
    this.id = id;
  }

  void addLink(uint l)
  {
    links ~= Link(l);
  }
}

struct Node2
{
  uint id;
  Array!(Link) links;

  this(uint id)
  {
    this.id = id;
  }

  void addLink(uint l)
  {
    links.insert(Link(l));
  }
}
struct Network(Node)
{
  Node[uint] nodes;

  void add(uint i, uint j)
  {
    if((i in nodes) is null)
      nodes[i] = Node(i);
    if((j in nodes) is null)
      nodes[j] = Node(j);

    nodes[i].addLink(j);
    nodes[j].addLink(i);
  }

  void print()
  {
    foreach(k; nodes.keys)
      {
        write("[", k, "]");
        foreach(l; nodes[k].links)
          write(" ", l.id);
        writeln();
      }
    writeln();
  }
}

unittest {
  Network!Node2 net2;
  net2.add(1, 7);
  writeln(net2);
}

Reply via email to