[Issue 1069] No error on type mismatch with varargs

Frits van Bommel fvbommel at REMwOVExCAPSs.nl
Tue Mar 20 03:19:35 PDT 2007


d-bugmail at puremagic.com wrote:
> I have expanded the example to show a bit more of the problem an end user can
> have (sorry I have tango hard-coded, just replace with printf):
> 
[snip]
>     this()
>     {   
>         add(&fn );     // Needed here

Correct

>         add(another);  // Not needed here!!!!

This happens to look like it does what it should, but in reality it 
still ads a delegate that will be invalid after the constructor returns. 
That delegate just happens not to reference the stackframe of the 
constructor, and thus not crash, because all it does is call a free 
function.
It's still undefined behavior, but undefined behavior doesn't 
necessarily means it'll crash (just that it *may* crash, or worse, and 
if it does it's your fault).

Also, adding a & won't help in this case, as it'll be a function pointer 
instead of a delegate...

>     }
[snip]
> void main()
> {   
>     auto val = new C;
>     add(another);     // Not here!

Correct, but only because the implicitly formed delegate literal happens 
not to go out of scope before it's last called. If for instance the 
module had a 'static ~this()' that would call 'call()' after main ended, 
it'd be undefined behavior.

>     call();
> }
> 
> This code works because by trial and error I have put the "&" in the right
> places.

That's not really the right strategy...
Just because it doesn't crash doesn't mean it does what you think it 
does, or that it won't crash the next time you upgrade/switch compilers 
(or just change which command-line switches to give to your current one)...

 > Can this kind of segfault be avoided be detecting it at the compile
> stage?

At least partially, yes. Google for "escape analysis" (Mostly applied to 
pointers, which have essentially the same problem when pointing to local 
variables).
It may not possible to catch 100% of all cases (without false positives) 
though, and it might be a lot of work to implement (not that I'm an 
expert in this).

> Regardless of the answer, I think a diagram (or more details) of what Frits
> explains in the first reply would help me understand. Thanks.

I'm not really good with diagrams.
Just remember: don't use delegates to local functions/delegate literals 
(including the implicit kind discussed here), pointers to local 
variables or references to 'scope' objects after the function they were 
created in returns.


More information about the Digitalmars-d-bugs mailing list