Function modifies string parameter without BYREF

From Liberty BASIC Family
Jump to navigation Jump to search

Description

A string variable passed as a parameter of a function may be modified on return from the function, even though the BYREF keyword was not specified. It should not be possible for a function to modify a parameter without BYREF.

Example code to demonstrate the bug

  actual$ = space$(255)
  void = BugTest(actual$)
  print actual$ ' should not be modified by function
  end

  function BugTest(formal$)
    l = len(formal$)
    calldll #kernel32, "GetModuleFileNameA", _
      0 as long, formal$ as ptr, l as ulong, _
      ret as ulong
    formal$ = left$(formal$, ret)
  end function

Example code to work around the bug.

  actual$ = space$(255)
  void = BugTest(actual$)
  print actual$ ' should not be modified by function
  end

  function BugTest(formal$)
    formal1$ = formal$ + chr$(0)
    l = len(formal1$)
    calldll #kernel32, "GetModuleFileNameA", _
      0 as long, formal1$ as ptr, l as ulong, _
      ret as ulong
    formal$ = left$(formal1$, ret)
  end function


Or, use the code below since the use of an additional string within the function is not required.

  actual$ = Space$(255)
  void = BugTest(actual$)
  Print actual$ ' should not be modified by function
  End

  Function BugTest(formal$)
    formal$ = formal$;chr$(0)
    l = Len(formal$)
    CallDLL #kernel32, "GetModuleFileNameA", 0       As long, _
                                             formal$ As ptr, _
                                             l       As ulong, _
                                             ret     As ulong
    formal$ = Left$(formal$, ret)
  End Function