Game Development Community

[beta5 bug] Bad string handling in GuiTreeViewCtrl::Item::getDisplayTextWidth()

by Manoel Neto · in Torque 3D Professional · 09/24/2009 (6:49 pm) · 1 replies

Found this one by accident, opening the editor in debug mode:

const S32 GuiTreeViewCtrl::Item::getDisplayTextWidth(GFont *font)
{
   if( !font )
      return 0;

   FrameAllocatorMarker txtAlloc;
   U32 bufLen = getDisplayTextLength();
   if( bufLen == 0 )
      return 0;

   char *buf = (char*)txtAlloc.alloc(bufLen);
   getDisplayText(bufLen, buf);

   return font->getStrWidth(buf);
}
This is a classical mistake: getDisplayTextLength() happens to return the string length, which is used to allocate a buffer. However this doesn't allocate the space for the NULL string terminator, allowing the string to be parsed beyond the buffer's bounds if whatever memory next to it isn't zero. This should be:


const S32 GuiTreeViewCtrl::Item::getDisplayTextWidth(GFont *font)
{
   if( !font )
      return 0;

   FrameAllocatorMarker txtAlloc;
   U32 bufLen = getDisplayTextLength();
   if( bufLen == 0 )
      return 0;

   //Add space for the NULL
   buffLen++;

   char *buf = (char*)txtAlloc.alloc(bufLen);
   getDisplayText(bufLen, buf);

   return font->getStrWidth(buf);
}