The program exits unexpectedly
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Dec 9 12:35:07 PST 2016
On 12/09/2016 08:50 AM, unDEFER wrote:
> On Friday, 9 December 2016 at 14:29:38 UTC, unDEFER wrote:
>> I'm afraid that the problem that my program wants to say something,
>> but there is no "flush" so message leaves in the buffer.
>
> I have found, it was code like:
>
> string path = "C:";
> string parent = path[0..path.lastIndexOf("\\")];
That's a bug because you're not checking the return value of
lastIndexOf. According to its documentation, lastIndexOf returns -1 if
it fails to find the needle:
http://dlang.org/phobos/std_string.html#.lastIndexOf
ptrdiff_t found = path.lastIndexOf("\\");
if (found == -1) {
// Not found
}
else {
// Now we can use it:
string parent = path[0..path.lastIndexOf("\\")];
// ...
}
The added complication is the fact that ptrdiff_t can be converted to
size_t and you get a huge string when doing path[0..path.lastIndexOf("\\")]
Do you have boundschecking turned off? It should catch such an error.
> And in mini program it works and shows diagnostic message.
> Where my diagnostic message in more complicate program???
Assuming boundschecking is turned off, I think you get unlucky in the
mini program and happen to hit a '\0' byte.
Ali
More information about the Digitalmars-d-learn
mailing list