Noob buffer problem Topic is solved

If you are using the main C++ distribution of wxWidgets, Feel free to ask any question related to wxWidgets development here. This means questions regarding to C++ and wxWidgets, not compile problems.
Post Reply
zobbo
Experienced Solver
Experienced Solver
Posts: 58
Joined: Sat Aug 18, 2007 4:41 am

Noob buffer problem

Post by zobbo »

Hello, having a buffer initialisation problem. using the following code:

Code: Select all

void MyFrame::Test3(wxSocketBase *sock)
{
 
  char len = NULL;// = NULL;
  char *buf7 = NULL;// = NULL;
  wxString s;
 
  len = 8;
  buf7 = new char[len];

 m_text->AppendText(_("Test 3 begins\n"));

  // This test is similar to the first one, but the len is
  // expressed in kbytes - this tests large data transfers.

  sock->SetFlags(wxSOCKET_WAITALL);

  // Read the data
  sock->Read(buf7, len);
  bool err = sock->Error();
  if(err == true){s.Printf(_("Error\n"));m_text->AppendText(s);}

  m_text->AppendText(_("Got the data\n"));
  s.Printf(_("Client says: %s\n"), buf7);
  m_text->AppendText(s);

 m_text->AppendText(s);
 s.Printf(_("Read %d\n"), sock->LastCount());
 m_text->AppendText(s);
  // Write it back
  sock->Write(buf7,len);
  delete[] buf7;

  m_text->AppendText(_("Test 3 ends\n\n"));
}
The problem I'm having is the buffer, buf7 is always assigned the values "
DavidHart
Site Admin
Site Admin
Posts: 4254
Joined: Thu Jan 12, 2006 6:23 pm
Location: IoW, UK

Post by DavidHart »

Hi,

The problem is that you're not null-delimiting buf7. So in the line:
s.Printf(_("Client says: %s\n"), buf7);
Printf has no way of knowing to stop at 8 bytes, and carries on adding junk.

One solution is to change your code to use create wxString s using the ctor:
wxString(const char* psz, wxMBConv& conv, size_t nLength = wxSTRING_MAXLEN)
and provide len or sock->LastCount() as the third parameter. Alternatively, change your code less, giving buf7 a size of len+1, and making buf7[8] = '\0'.

Regards,

David
zobbo
Experienced Solver
Experienced Solver
Posts: 58
Joined: Sat Aug 18, 2007 4:41 am

Post by zobbo »

Brilliant, thanks. I knew it was something silly. I took the latter option, just due to laziness, but using the wxString constructor looks like a more sensible way to do it when I'm doing something proper.

Thanks a lot,

Zobbo
Post Reply