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?

Kromster
  • 7,181
  • 7
  • 63
  • 111
durumdara
  • 3,411
  • 4
  • 43
  • 71

2 Answers2

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.

Uwe Raabe
  • 45,288
  • 3
  • 82
  • 130
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);
HeartWare
  • 7,464
  • 2
  • 26
  • 30