When you call Insert()
, the memory manager will move the AnsiString
to a new location in memory if there isn't enough additional contiguous memory to extend the buffer in its current memory location. This leaves p
pointing to the old memory location, which does not hold the modified string, and will likely lead to access violations.
Adding one line of code to reinitialize p
after each Insert()
statement fixes the problem.
var
s: AnsiString;
p: PAnsiChar;
offset, idx, cnt: Integer;
begin
s := 'some>very>long>string>with>field>delimiters>';
p := @s[1];
offset := 1;
// find the 5th field
cnt := 5;
repeat
idx := AnsiString.AnsiPos('>', p);
Inc(p, idx);
Inc(offset, idx);
Dec(cnt);
until cnt = 0;
// insert a new field after the 5th field
Insert(AnsiString('something new>'), s, offset);
p := @s[offset]; // <- this fixes the issue
// skip other fields
// insert other values
// repeat
end;