Var

strl, str2: string; buffer: TBytes; begi n strl := 'Hello world';

SetLength (buffer, Length (strl)); Move (strl[l], buffer[l], Length (strl));

SetLength (str2, Length (buffer));

As Length returns the number of two-byte characters and Move works in bytes, only the first half of the string the string is copied to the buffer and then to the second string with the trailing part of the target string full of whatever data was in its uninitialized memory:

| Hello world becomes Hello±LM;Bwe

If you have existing code that uses strings as buffers (like in the example above) and don't want to touch your code, a solution might be to change the string type definition to RawByteString (or, to a lesser extent, AnsiString). The same MoveStrings demo has the same algorithm with the strings declared as: var strl, str2: RawByteString;

This version of the code produces the proper output, as it will be by using AnsiString. Depending on the circumstances (the actual meaning of the data being moved, string or buffer with data), you might prefer one of these types over the other.

Even better, whenever possible, change your code to use a dynamic array of bytes like TBytes, the data structure I've used in the code snippet of this section to hold a generic buffer. The TBytes type is defined in the SysUtils unit as a dynamic array of bytes: type

TBytes = array of Byte;

Was this article helpful?

0 0
Project Management Made Easy

Project Management Made Easy

What you need to know about… Project Management Made Easy! Project management consists of more than just a large building project and can encompass small projects as well. No matter what the size of your project, you need to have some sort of project management. How you manage your project has everything to do with its outcome.

Get My Free Ebook


Post a comment