cStringBuilder access unowned memory when you append a String larger than the chunk size

Summary

Id: 2314.3
Type: Bug Bug
Current Status: Resolution Identified

Detail

12 Nov 2003 Resolution Identified Luke

I've been using your cStringBuilder Class, which has been exactly what I've needed, helping to optimize one of my biggest bottlenecks. But it also had caused a problem, and I don't want other programmers to have to experience this as well. If you append a string that is much larger than the chunk size, then it attempts to copy memory beyond the end of the string, and is yanked of the windows stage very quickly. It is rather simple to fix, but it was harder to diagnose because it appeared random; sometimes it would crash, and sometimes not... Anyway, here's what I did:

I replaced

Dim lLen As Long
 
   ' Append an item to the string:
   lLen = LenB(sThis)
   If (m_iPos + lLen) > m_iLen Then
      m_sString = m_sString & Space$(m_iChunkSize \ 2)
      m_iLen = m_iLen + m_iChunkSize
   End If

in the Append Method with

Dim lLen As Long
Dim lLenPlusPos As Long
 
   ' Append an item to the string:
   lLen = LenB(sThis)
   lLenPlusPos = lLen + m_iPos
   If lLenPlusPos > m_iLen Then
      Dim lTemp As Long
      
      lTemp = m_iLen
      Do While lTemp < lLenPlusPos
         lTemp = lTemp + m_iChunkSize
      Loop
      
      m_sString = m_sString & Space$((lTemp - m_iLen) \ 2)
      m_iLen = lTemp
   End If

Seems to work better.