Menu

#966 Weird behavior in fix-len string (Dim As String * N ...) if explicit NULL character (Chr(0)) used in a string expression

open
nobody
None
compiler
2024-04-11
2022-07-14
No

Use explicit NULL character (Chr(0)) in a string expression involving a fixed length string variable (Dim As String * N ...) can lead to different unexpected results depending on usage context (initialization, assignment, concatenation, ...).
Depending on the case, the explicit NULL character (chr(0)) in the expression is considered or not to be the terminal character of the string expression (truncating the continuation).

Demonstrative example with fix-len string (different unexpected results depending on usage context):

Dim s1 As String * 20 = "Alpha" + Chr(0) + "Beta"
Print s1
Print "'" & s1 & "'"
Print
Dim As String * 20 s2
s2 = "Alpha" + Chr(0) + "Beta"
Print s2
Print
Dim As String * 20 s3 = s1
Print s3
Print
Dim As String s = s1
Print s

Sleep

Output:

Alpha Beta
'Alpha'

AlphaBeta

Alpha

Alpha

For more information, see https://www.freebasic.net/forum/viewtopic.php?t=31753&sid=ee9433d22f0916e860f6c3779876998b


No problem with (fix-len) zstring:

Dim z1 As Zstring * 20 = "Alpha" + Chr(0) + "Beta"
Print z1
Print "'" & z1 & "'"
Print
Dim As Zstring * 20 z2
z2 = "Alpha" + Chr(0) + "Beta"
Print z2
Print
Dim As Zstring * 20 z3 = z1
Print z3
Print
Dim As String s = z1
Print s

Sleep

Output:

Alpha
'Alpha'

Alpha

Alpha

Alpha

Discussion

  • fxm (freebasic.net)

    For now, a warning has been added in the documentation:

    Note: It is not recommended to use explicit NULL character (chr(0)) in a string expression involving a fixed length string variable because this can lead to different unexpected results depending on usage context (initialization, assignment, concatenation, ...).

     
  • Jeff Marshall

    Jeff Marshall - 2022-07-16

    Related: [#753], [#729]

     

    Related

    Bugs: #729
    Bugs: #753

  • fxm (freebasic.net)

    The new definition of the 'STRING*N' datatype (since fbc 1.20.0) solves the problem.

     

Log in to post a comment.

MongoDB Logo MongoDB