Segmentation fault from using SList in a class?

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jun 6 03:10:27 PDT 2015


On Saturday, June 06, 2015 09:44:36 Tim K. via Digitalmars-d-learn wrote:
> Hello!
>
> I just started learning D and I come from a mostly C and C#
> background.
> Hello World was working, so I figured that I should try something
> more complex: a template class and si I went with a simple stack.
>
> Using dmd the code I wrote causes a segmentation fault and I am
> not sure why.
>
> import std.stdio;
> import std.container.slist;
>
>
> class Stack(T)
> {
>      SList!(T) s;
>      this() {}
>      void push(T element)
>      {
>          s.insertFront(element);
>      }
> }
>
> int main()
> {
>      Stack!(int) x;
>      writeln("1");
>      SList!(int) p;
>      writeln("2");
>      p.insertFront(42);
>      writeln("3");
>      x.push(42);
>      writeln("4");
>      return 0;
> }
>
>
> This program prints the following into the console:
> % dmd test.d && ./test
> 1
> 2
> 3
> zsh: segmentation fault  ./test
>
>
> I do not understand why the normal SList works fine but the one
> inside the object doesn't. What am I overlooking?

>From the looks of it, you never initialized x, so it's null. So, the problem
has nothing to do with SList. It's the fact that you're trying to
dereference a null reference. You need to call new to allocate a Stack!int,
not just declare a reference to one.

void main()
{
    Stack!int x
    x.push(42);
}

would have exactly the same problem. You need something like

auto x = new Stack!int;

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list