Uploaded image for project: 'Axis-C++'
  1. Axis-C++
  2. AXISCPP-825

delete/delete[] mismatch in XercesHandler.cpp

    XMLWordPrintableJSON

Details

    Description

      The function:

      void XercesHandler::characters(const XMLCh* const chars, const unsigned int length)

      has some memory management problems. The most obvious problem is that the memory allocated with new[] is deleted with delete (change the two delete statements to delete[] statements). But another problem is that the memory deleted sometimes was allocated by new[] and sometimes via Xerces' XMLString::transcode(). Currently XMLString::transcode() allocates memory using new[], but this may not always remain true. Calls to XMLString::transcode() should be matched by calls to XMLString::release().

      The quick fix is to change delete to delete[]. But in the long run it is better not to use pointers at all and just deal with std::strings (this is internal code). I think this will lead to fewer bugs and memory leaks and will not noticeably affect performance.

      So the quick fix looks like this:

      char* cp_CurrentNameOrValue = XMLString::transcode(chars);
      char* cp_FullNameOrValue = new char[strlen(cp_PreviousNameOrValue) + strlen(cp_CurrentNameOrValue) + 1];
      strcpy(cp_FullNameOrValue, cp_PreviousNameOrValue);
      strcat(cp_FullNameOrValue, cp_CurrentNameOrValue);
      m_pNextElement->m_pchNameOrValue = (const char*)cp_FullNameOrValue;
      delete[] (const_cast <char*> (cp_PreviousNameOrValue));
      delete[] cp_CurrentNameOrValue;

      I also changed one strcat to strcpy to make the code more readable (and one line shorter). Another comment is that const casts can be dangerous and lead to confusing code.

      Attachments

        Issue Links

          Activity

            People

              cdinapala Chinthana Dinapala
              hnordberg Henrik Nordberg
              Votes:
              0 Vote for this issue
              Watchers:
              0 Start watching this issue

              Dates

                Created:
                Updated:
                Resolved: