Microsoft KB Archive/250914

= BUG: Modifying String During Concatenation May Yield Unexpected Results =

Article ID: 250914

Article Last Modified on 5/12/2003

-

APPLIES TO


 * Microsoft Visual Basic 6.0 Enterprise Edition
 * Microsoft Visual Basic 6.0 Professional Edition
 * Microsoft Visual Basic 6.0 Learning Edition

-



This article was previously published under Q250914



SYMPTOMS
A line of code concatenates a string with an in-line call to a function that modifies the first string and returns another string, but the resulting concatenated string is not what was expected.



RESOLUTION
To work around this problem, define an intermediate string variable to hold the value that is returned from the function, and then use this string in the concatenation. For example: s1 = "String1" s2 = GetString2(s1) sTmp = s1 & s2



STATUS
Microsoft has confirmed that this is a bug in the Microsoft products that are listed at the beginning of this article.



MORE INFORMATION
If you modify a string in a function and that function is part of a string concatenation, Visual Basic reuses the buffer incorrectly. For example, you might have the following code, in which s1 gets modified in the function GetString2: s1 = "String1" sTmp = s1 & GetString2(s1) MsgBox sTmp

Function GetString2(sStr As String) As String sStr = "XYZ" ' This should also modify s1 in Command1_Click GetString2 = "String2" End Function You would expect that sTmp would contain "XYZString2". Instead, it contains "String2String2".

The problem occurs when you run the program inside the Visual Basic Integrated Development Environment (IDE) and you compile the program in p-code and then run the standalone executable. This does not happen with an executable file compiled in native code.

Steps to Reproduce Behavior
 Create a new Standard EXE project in Visual Basic. Form1 is created by default. Add a CommandButton to Form1.  Paste the following code into the code window of Form1. Option Explicit

Private Sub Command1_Click Dim s1 As String Dim sTmp As String s1 = "String1" sTmp = s1 & GetString2(s1) MsgBox sTmp End Sub

Function GetString2(sStr As String) As String sStr = "XYZ" ' This should also modify s1 in Command1_Click GetString2 = "String2" End Function  Run the project and click on the button to see the concatenated string.

Additional query words: ampersand

Keywords: kbbug kbnofix kbstring kbideproject KB250914

-

[mailto:TECHNET@MICROSOFT.COM Send feedback to Microsoft]

© Microsoft Corporation. All rights reserved.