Context 1
var text:String;
text:=\'hello\';
myFunc(text);
Context2
function myFunc(mytext:String);
var textcopy:String;
b
Memory management for Delphi strings is a little unusual. After you call myFunc(text)
, and assign textcopy := mytext
, all three variables (text
, mytext
and textcopy
) will be pointing to the same address, that of the original string.
But as soon as you use one of these variables to make changes to the string, Delphi clones the string behind the scenes, and your changes are applied to the copy. The other two variables still point to the original, so they remain unchanged. So any changes made in Context 2 will not be seen in Context 1 - this "copy-on-write" mechanic effectively gives you pass-by-value semantics. All of these strings are reference-counted, and will be freed automatically once all references go out of scope.
However, there is an exception. If you access the string using pointers, rather than string operations, you'll bypass the copying step and your changes will affect the original. You'll also bypass the reference counting logic, and potentially end up with a pointer to a deallocated block of memory. This may be the reason behind your access violation, but I couldn't say without more details / more code.
If you want reference passing, declare your function as myFunc(var mytext: String)
. If you want to force Delphi to copy the string, instead of waiting until it's modified, you can use System.UniqueString.