[fpc-devel] Strange Problem!
Jonas Maebe
jonas.maebe at elis.ugent.be
Wed Apr 25 22:48:03 CEST 2012
On 25 Apr 2012, at 22:11, Amir wrote:
> I am not sure what you mean be "your program is not valid".
This is not valid when Result is an ansistring (or unicodestring), at least if you afterwards start writing to Result via the CurDigits pointer:
> Result:= ' ';
>
> CurDigit:= @(Result [MaxLength]);
The reason is that ansistring is an implicit pointer type, unlike shortstring. Assigning a constant ansistring to Result means simply that a pointer to that series of spaces is copied into the Result pointer. If you then start modifying Result by hacking behind the compiler's back (which is what you do by using a pointer), the compiler cannot make a copy of that constant string and you start modifying the original constant data that was stored in the program. As a result, when you call the function again, the first assignment will assign whatever you stored in that constant during the previous execution of your function rather than a series of spaces.
The solution is to create a local copy of the constant before you start modifying it, which you can do by adding e.g. setlength(Result, length(Result)) after the first assignment.
In summary: do not use pointers unless you know in detail how the compiler implements a particular data structure. Using pointers is like using assembler: it can result in fast code, but it's an excellent way to shoot yourself in the foot.
Jonas
More information about the fpc-devel
mailing list