Var
S:String;
P:Pchar;
begin
S := 'test';
P := Pchar(S);
P^ := UpCase(P^); // upcase the first one... etc.
//Crash
End;
I've already figured out why and worked around it but others claim to see no error..
As
Leledumbo mentioned, this is indeed by design. You're assigning a constant string to an AnsiString. The compiler won't insert a copy in this case, but instead use the constant string record contained in the readonly
.rdata section of the binary (which has reference count -1 by the way). When you cast that to a
PChar you simply get the pointer to the first element of the readonly data. And changing that will be blocked by the memory protection of the operating system (so in DOS it would work
).
na, its faulting because it is trying to change READ only memory when there Is a change to do.
and that behavior depends on the setting of the longstring directive. if "string" means "shortstring" then it won't fault.
ShortString does not support a direct conversion to
PChar. You need to use
PChar(@s[1]) and you need to make sure manually that your
ShortString ends with
NUL (as the compiler ensures that only for the managed string types as well as strings directly assigned to
PChars).