The African Chief wrote:
However, I fail to see the problem with Str2pChar. It works correctly in all my tests (at least, under BP7, BPW, Delphi 1 and Delphi 2).
...which is a nice example for the fact that testing alone doesn't prove correctness... ;-)
First of all, there is a problem if s has full length, and "s+Chr(0)" would overflow s. Currently this is not noted (a bug in GPC), but when the bug is fixed, it will either trigger a runtime error or cut the result, i.e. not append the #0.
In BP (which doesn't have this bug and always cuts strings), the routine indeed behaves wrong is this situation. See the following program:
program x;
Function Str2pChar ( Var s : String ) : pChar; Var x : String; Begin x := s; s := s + Chr ( 0 ); Str2pChar := @s [1]; s := x; End; {* str2pChar *}
const s:string=' '+ ' '+ ' '+ ' '+ ' '#13#10'This program is OK.'; t:string=#8#8#8#8'wrong, sorry.'#0;
var p:pchar;
begin p:=str2pchar(s); writeln(p); end.
Secondly, you copy back the old value of s back afterwards. This only works because GPC copies only Length(x) characters. If this behaviour would be changed to copy more characters (of course not more than x.Capacity), your code would break. (Such a change might be done for efficiency, e.g. by rounding up to a multiple of 4, and though I don't think it's likely to be changed, the change would be valid, AFAIK, since the characters after Length(x) in a string are undefined.)
A possible "fix" for the second problem (not the first one, though the appearance of the problem will be different then) would be "s[Length(s)+1]:=#0" (also, it's much more efficient).
But don't worry too much about these functions. Sooner or later, such functionality will be built-in into GPC...
Frank
-- Frank Heckenbach, Erlangen, Germany heckenb@mi.uni-erlangen.de http://home.pages.de/~fjf/links.htm