xsharp.eu • X# 2.10 and String2Psz() in struct members
Page 1 of 1

X# 2.10 and String2Psz() in struct members

Posted: Wed Feb 02, 2022 4:34 pm
by Bernhard Mayer
Dear X# DevTeam!

The new X# 2.10 compiler has a new warning "String2Psz() and Cast2Psz() should only be used for variables that have a 'local' scope. The allocated PSZ will be automatically released once the current function/method ends."

Imagine a struct (Either global or local) strLine containing a PSZ member called pTitle; currently the compiler throws a warning when assigning data to this member.

Code: Select all

// current code
strLine:pTitle := String2Psz(oData:ItemNo) // oData:ItemNo = string variable
What is the proper way to assign the data?

BR,
Bernhard

X# 2.10 and String2Psz() in struct members

Posted: Wed Feb 02, 2022 4:44 pm
by robert
Bernhard,
This is difficult to answer without seeing:
- how the variable is declared
- how the variable is used

In general:
- if the variable is declared with IS somestruct then you can safely use String2psz() because the variable will go out of scope when the function ends anyway
- if the variable is declared with AS SomeStruct then it depends if you are only using the variable inside the function where it is declared (so MemAlloc() and MemFree() happen inside the same function). In that case you can ignore the warning

- If the MemAlloc() or the String2Psz() for the structure is in another function / method than the MemFree() then after the function ends where the String2psz() is used then the structure will have a reference to a PSZ that is no longer there. This could cause problems. Of course there will be no problems when you do not attempt to read the PSZ, but I would not take that risk.

If you do not like the warning then use:
- StringAlloc() to allocate the PSZ
- MemFree() to free the PSZ when it is no longer needed

Robert