String copying fails when output from assert
Jonathan M Davis
newsgroup.d at jmdavisprog.com
Tue Nov 21 19:22:54 UTC 2017
On Tuesday, November 21, 2017 18:59:14 David Zhang via Digitalmars-d-learn
wrote:
> On Tuesday, 21 November 2017 at 18:56:03 UTC, Adam D. Ruppe wrote:
> > On Tuesday, 21 November 2017 at 18:49:40 UTC, David Zhang
> >
> > wrote:
> >> assert(false, chars[0..str.length]);
> >>
> >> }
> >>
> >> What am I missing here?
> >
> > You're escaping a reference to a local variable there. chars[]
> > is a pointer to the stack, which is promptly smashed when the
> > assert error starts working up the call chain, so by the time
> > it actually prints, you have undefined behavior.
>
> So I'd have to allocate the buffer on the heap then...
> Is there any way to do this without allocating to the stack?
Why would you need to allocate on the stack to allocate on the heap? If you
have a string to pass assert for its message, then just pass it the string.
If you have a char[], then idup it. If you have a static array on the stack,
then idup it. And if you're iduping in the assert statement, then it should
only idup when the assertion fails.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list