Tuesday, November 30, 2010

Bugs aligned to CString

Today I noticed a funny thing. Class CString C++ sometimes works like class String in Java
For example :
class Example
{
  CString mName;

public: 
  void setName(const CString & name)
  {
     mName = name; 
  }
  void modify()
  {
     memset((VPVOID)(LPTSTR) mName,65,mName.GetLength()*sizeof(TCHAR));
  }
}

class Other
{
// we set up this name somewere in code 
public: 
  CString getName() const
  {
     return mName; 
  } 
}


void main()
{
   std::autoptr o1 =
std::autoptr(new  Other(_T("simple string")));
   Example ex1;
   ex.setName( o1->getName() );
   ex.modyfy();
   // here you will have empty string for o1 and for ex classes 
   // because it refers to the same string data in memory 

   // so both classes will contain modified data
 



Conclusion : don't mix API because you never know about class implementation.
Fix is simple, just use mText.Empty() or mText[n] to modify string and never (LPTSTR)(mText)[n]

No comments: