2
function leftstr(s:string; n:Integer):string;
var
i:integer;
t:string;
begin
//init var t
t := '';
for i := 0 to n do
begin
//main loop
t := t + s[i];
end;
//return results
Result:=t;
end;

So when I run this function and use ShowMessage to get the value of t in each increment of i, t is always blank. Can someone tell me the problem? This is compiled using Delphi XE6

0

1 Answer 1

5

The problem is that strings use 1-based indexing and you are accessing out of bounds. Your loop should be:

for i := 1 to n do

Probably what happens is that s[0] refers to some part of the string's meta data (length or reference count, I cannot remember which) that happens to contain a zero byte. This is then interpreted as a null terminator when the string is passed to ShowMessage.

If you had enabled the range checking feature in your compiler options, the compiler would have inserted code that would have found the error for you. This range checking feature is an astonishingly neglected and overlooked feature.


Of course, the function is a little pointless, as well as rather inefficient. You can use LeftStr from the StrUtils unit. Or plain old Copy from the System unit.

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

9 Comments

Yes use Copy. If s is blank, then s[i] will return an access violation.
In Delphi, and Pascal before it, the string data type has reserved element 0. It used to be the length of the array for Pascal and may still be for short strings (less than 255 in length). The details of the structure of a string is available in the Delphi help.
@EchelonKnight In desktop Delphi (i.e. not mobile zero based strings), then s[0] is an out of range error. Remember that we are talking about string and not about short strings, which are a completely different type. There is absolutely no reserved element 0 in a string. You are very much mistaken in thinking so.
The Delphi documentation shows that elements 0 and further "to the left", ie. Negative, contain metadata pertaining to the size and allocation or the string. All of these are out of range as far as the compiler is concerned, but the space is still reserved for the string.
@EchelonKnight For a non-empty string that might be true today but it is implementation detail, subject to change, non-existent for an empty string, and you cannot expect to access that metadata using []. Why would you try to do that?
|

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.