Visual Basic 6中的字符串空间不足
我们在通过TCP套接字来回发送数据的VB6应用程序中遇到错误。我们收到"字符串空间不足"的运行时错误。有没有人看到这件事或者对为什么会发生这样的事情有任何想法?似乎我们达到了某些VB6阈值,因此任何其他想法也将有所帮助。
,
ak
解决方案
在MSDN上找到的文本:
http://msdn.microsoft.com/zh-CN/library/aa264524(VS.60).aspx
Visual Basic for Applications Reference Out of string space (Error 14) Specifics Visual Basic permits you to use very large strings. However, the requirements of other programs and the way you manipulate your strings may cause this error. This error has the following causes and solutions: Expressions requiring that temporary strings be created for evaluation may cause this error. For example, the following code causes an Out of string space error on some operating systems:
MyString = "Hello" For Count = 1 To 100 MyString = MyString & MyString Next Count
Assign the string to a variable of another name. * Your system may have run out of memory, which prevented a string from being allocated. Remove any unnecessary applications from memory to create more space. For additional information, select the item in question and press F1.
假设我们要在循环中追加数据,请确保没有将其追加到自身上,这将非常快地消耗内存。
错误含义的示例和说明:
http://msdn.microsoft.com/en-us/library/aa264524.aspx
正如其他人指出的那样,VB中的每个字符串连接都将分配一个新字符串,然后复制数据,然后在可以的情况下重新分配原始数据。在一个循环中,这可能会导致问题。
要解决此问题,我们可以创建一个简单的StringBuilder类,如下所示:
Option Explicit Private data As String Private allocLen As Long Private currentPos As Long Public Function Text() As String Text = Left(data, currentPos) End Function Public Function Length() As Long Length = currentPos End Function Public Sub Add(s As String) Dim newLen As Long newLen = Len(s) If ((currentPos + newLen) > allocLen) Then data = data & Space((currentPos + newLen)) allocLen = Len(data) End If Mid(data, currentPos + 1, newLen) = s currentPos = currentPos + newLen End Sub Private Sub Class_Initialize() data = Space(10240) allocLen = Len(data) currentPos = 1 End Sub
此类将通过强制在字符串中使用空格来构建字符串,然后根据需要覆盖空格来最大程度地减少字符串分配的数量。如果发现它没有足够的预初始化空间,它将对其重新分配以使其大小大约增加一倍。 Text方法将返回实际使用的字符串部分。
听起来我们经常要添加一个字符串。我们可以尝试使用StringBuilder类
另外,可能是我们有一些陈旧的对象,这些对象包含闲置的字符串,这些字符串没有被使用,应该释放。也许通过在Class_Initialize / Class_Finalize
中记录对象分配/释放来检查循环引用。
除了Jacco的响应外,vbAccelerator还具有出色的String Builder类,该类可以完成几乎相同的操作,但功能更强大。作者还逐步介绍了解决方案,并解释了其工作原理。
在2009年春季的某个时候,Microsoft进行了XP更新,干扰了Armadillo / Silicon Realms包装程序。
引发错误14的代码行超出字符串空间不合逻辑。字符串太大没有问题。这是一个简单的任务,我什至将其更改为" foo",并且仍然发生错误14. 我认为错误在XP中的映射不正确。
我们的答案是从Armadillo保护项目中删除copyMem-11,然后重新包装exe。