Compiler bug or incorrect usage for pointer of Struct?
Temtaime
temtaime at gmail.com
Sat Jan 13 13:54:28 UTC 2018
On Saturday, 13 January 2018 at 12:22:17 UTC, Heromyth wrote:
> When executing the test code, it will exit abnormally. It seems
> *this.output* is pointing a free memory when executing
> *writer.write(dom)*.
>
> I'm not sure whether there is a bug in the compiler. If it is,
> I can file a bug. If not, somebody can tell me how to fix this.
>
> Thanks!
>
> Here is my test code (You can test it in
> https://run.dlang.io/is/0OPBVI):
>
> ==============================
> import std.stdio;
>
> void main()
> {
> bugTest();
> }
>
> // This code is stripped from
> https://github.com/Kozzi11/experimental.xml/blob/master/source/std/experimental/xml/writer.d
> void bugTest()
> {
> string dom = "XML DOM";
>
> auto file = File("catalogue.xml", "w");
>
> // It's OK
> // auto textWriter = file.lockingTextWriter;
> // textWriter.writerFor.write(dom);
>
> // There's a bug
> auto writer = writerFor(file.lockingTextWriter);
> writer.write(dom);
>
> file.close();
> }
>
> auto writerFor(OutRange)(auto ref OutRange outRange)
> {
> auto res = Writer!(OutRange)();
> res.setSink(outRange);
> return res;
> }
>
> struct Writer(OutRange)
> {
> private OutRange* output;
>
> void setSink(ref OutRange output)
> {
> this.output = &output;
> writeln("in setSink: ", this.output);
> }
>
> // void setSink(typeof(output) output)
> // {
> // this.output = output;
> // }
>
> void write(string s)
> {
> writeln("in write: ", output);
> output.put(s);
> }
> }
It's your bug.
file.lockingTextWriter does not return a reference.
It is passed to writerFor as a copy on the stack and in setSink
you get a pointer of a stack variable that gets killed after
writerFor returns.
More information about the Digitalmars-d
mailing list