X# 2.10 and String2Psz() in struct members

This forum is meant for questions and discussions about the X# language and tools
Post Reply
Bernhard Mayer
Posts: 52
Joined: Thu Oct 06, 2016 3:00 pm
Location: Austria

X# 2.10 and String2Psz() in struct members

Post 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
User avatar
robert
Posts: 4520
Joined: Fri Aug 21, 2015 10:57 am
Location: Netherlands

X# 2.10 and String2Psz() in struct members

Post 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
XSharp Development Team
The Netherlands
robert@xsharp.eu
Post Reply