On 12/27/2013 01:40 AM, Jonathan wrote:

Term makeExTerm(){
     Term var1 = Term(1);//x
     Term var2 = Term(2);//y
     Term var3 = Term(3);//z
     Term fxx = Term(4, [&var1,&var1]);//f(x,x)
     Term gfxxy = Term(5, [&fxx,&var2]);//g(f(x,x),y)
     Term hzg = Term(6, [&gfxxy,&gfxxy]);//h(g(f(x,x),y),g(f(x,x),y))
     return hzg;
}

Using the above, I wrote a test program,
...

Can anyone tell me what is going on?

You are taking the address of stack-allocated variables. [1]
Accessing the terms after the function has returned results in undefined behaviour. In the case where it worked you just were lucky.

You may allocate your terms on the heap using 'new':
---
Term* makeExTerm(){
    auto var1 = new Term(1);//x
    auto var2 = new Term(2);//y
    auto var3 = new Term(3);//z
    auto fxx = new Term(4, [var1,var1]);//f(x,x)
    auto gfxxy = new Term(5, [fxx,var2]);//g(f(x,x),y)
    auto hzg = new Term(6, [gfxxy,gfxxy]);//h(g(f(x,x),y),g(f(x,x),y))
    return hzg;
}

void main(string[] args){
    auto exTerm = makeExTerm();
    string printable = termToString(exTerm);
    writeln(printable);
    exTerm.term.terms.Subterms[0].term.terms.Subterms[0] = new Term(219);
    // it is now  (and should be) h(g(e,y),g(e,y))
    string printable2 = termToString(exTerm);
    writeln(printable2);
}
---

prints:
---
h(g(f(x,x),y),g(f(x,x),y))
h(g(e,y),g(e,y))
---

[1] This would be disallowed in the memory safe subset. You might want to put '@safe:' on top of your files.

Reply via email to