title: Delphi AnsiString Manipulation - PAnsiChar becomes corrupt?
body: <p>I use the following approach to move through and manipulate an <code>AnsiString</code>.  It works most of the time, but sometimes the pointer into the string quits functioning.  Given the following code:</p>
  
  <pre><code>var
    s: AnsiString;
    p: PAnsiChar;
    offset, idx, cnt: Integer;
  begin
    s := 'some&gt;very&gt;long&gt;string&gt;with&gt;field&gt;delimiters&gt;';
    p := @s[1];
    offset := 1;
  
    // find the 5th field
    cnt := 5;
    repeat
      idx := AnsiString.AnsiPos('&gt;', p);
      Inc(p, idx);
      Inc(offset, idx);
      Dec(cnt);
    until cnt = 0;
  
    // insert a new field after the 5th field
    Insert(AnsiString('something new&gt;'), s, offset);
  
    // skip other fields
    // insert other values
    // repeat
  end;
  </code></pre>
  
  <p>When debugging, just after the <code>repeat..until</code> loop finishes you can look at the inspector and see that <code>p = 'field&gt;delimiters&gt;'</code>.  After the <code>Insert()</code> statement, <code>s = 'some&gt;very&gt;long&gt;string&gt;with&gt;something new&gt;field&gt;delimiters&gt;'</code> and <code>p = 'something new&gt;field&gt;delimiters&gt;'</code> in the inspector.  This is as expected.</p>
  
  <p>My real string is several thousand characters long.  This method of moving through the string and adding new fields works dozens of times, then it suddenly stop working.  <code>p</code> no longer shows the inserted value at the front of the string after the call to <code>Insert()</code>.  <code>p</code> doesn't seem to know that <code>s</code> has changed...</p>
  
  <p>Why does <code>p</code> properly reference a character on <code>s</code> after most <code>Insert()</code> statement, and suddenly stop working after some calls to <code>Insert()</code>?</p>
  
  <p><em>(I discovered the answer to my question while typing it up.  The answer seems obvious now, but not so while I was struggling with the issue.  Perhaps posting the question and the answer will help someone else...)</em></p>