2

Delphi Seattle (S10). Win32 project.

Yesterday I got wrong result in my old routine. I found this line:

sPre := Copy(aSQLText, p - 1, 1);

aSQLText was 'CREATE', and p = 1.

The sPre got "C" result.

Hmmm... Then I wrote to watch window:

Copy('ABC', 0, 1)

and the result was "A"...

Ouch... What???

The copy handles the overflow in the end well. But not at the beginning? Or what?

I hope that I haven't got any codes which points to before the string.

Do you also got this result in your Delphi? Why?

As I know the strings internally stored as 4 byte length + string; and they based in 1 (not 0 as any arrays). Is this a bug?

2 Answers 2

4

The call to copy in your code is resolved to the internal function _UStrCopy from System.pas. Right in the beginning of its implementation it checks the Index and Count parameters and corrects them when necessary. This includes forcing the Index to point to the first character if it is too low.

I agree that this should be documented, though.

Sign up to request clarification or add additional context in comments.

Comments

0

The documentation for Copy doesn't specify what will happen in this instance, so I wouldn't call it a Bug per se.

I can see arguments for both solutions (empty string or as it does, assume 1 as starting position).

Point is, as it is not defined in the documentation what happens in this instance, it is unwise for a program to assume anything one way or another, as it may be implementation dependent and might even change over the course of different versions. If your code can risk having p=1 (or even p=0) and you want the empty string in that case, you should explicitly write code to that effect instead of relying on your (wrong, in this case) expectation on what the compiler might do:

if p<=1 then sPre:='' else sPre := Copy(aSQLText, p - 1, 1);

2 Comments

Thank you, I make this change in my code. But this a new source of bugs, I need to remember this in my any parse routines. :-(
"new" source of bugs? Has been like that for at least 10 years and probably longer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.