On Tuesday, November 21, 2017 19:13:36 David Zhang via Digitalmars-d-learn wrote: > On Tuesday, 21 November 2017 at 19:05:21 UTC, Jonathan M Davis > > wrote: > > Well, the assertion is going to throw an AssertError, which > > takes a string for its message. It doesn't copy the contents of > > the string. It's just taking a slice just like whenever you > > pass a string to any other function. So, it refers to the same > > memory as what's passed in. So, if what it's passed is a string > > that refers to memory on the stack, then when it goes to print > > the message, it's going to be garbage, because the stack was > > unwound, and the static array is gone. > > > > Honestly, I'd argue that it's a bug that it allows you provide > > a message as a char[] instead of immutable(char)[]. It seems > > that the compiler is implicitly converting char[] to > > immutable(char)[] in this case, which is very bad. It would > > matter less if you were giving the assertion a char[] that > > referred to memory on the heap, but it still shouldn't be > > allowed. > > > > You really should be giving assertions a value that is an > > actual string that lives on the heap when providing a message, > > not a char[], and definitely not a char[] that's a slice of a > > static array. > > > > - Jonathan M Davis > > Right. So a literal would work, because it's in the .data > segment, or inlined. Basically, only strings from the heap, or > that are compiled into the code are valid for assert messages.
Or any kind of exception message. > What kind of behavior would an assert from stdc have (id, > betterC)? I don't know. It calls the C implementation at that point, so it won't throw an AssertError, but I don't know exactly how it's implemented. It probably just prints the message and then kills the program, so it'll probably work even with a slice of a static array, but I don't know for sure. However, unless the code is specifically versioned to only be betterC, it would be a really bad idea to rely on that behavior. And if assert ever gets fixed such that it properly rejects messages that aren't actually strings, passing it a char[] wouldn't work anymore anyway. - Jonathan M Davis