[xml] xmlNewNode allocates memory that ist already in use

Thomas Kutzer wrote:

With the second solution a new problem occured which I want to describe

Following two lines of code:

      temp2 = (xmlChar *)IntToStr(i_value).c_str();
      nodePtr3 = xmlNewTextChild(NodePtr3, NULL, (xmlChar *)"value",

After the call of xmlNewTextChild there is just "0" in the part of memory
to which temp2 adresses.

This is NOT a problem with libxml2, the Borland compiler, its runtime library or byte alignment. It IS a problem with the way Thomas is using a C++ "temporary" object.

In this example, the Borland runtime's IntToStr function returns an object of type String. This object's c_str() member function returns a pointer to its internal string buffer, and this pointer is then stored in "temp2". But once this statement has executed, the String object goes out of scope, and so its destructor is called. This leaves temp2 holding an invalid pointer, since it points to an address which has been deallocated.

The same problem would occur with the following equivalent code, but here the scoping problem is a little more explicit.

   String s = IntToStr(i_value);
   temp2 = (xmlChar *)s.c_str();
 } // At this point, s is destroyed; temp2 now points to freed memory!
 nodePtr3 = xmlNewTextChild(NodePtr3, NULL, (xmlChar *)"value", temp2);

xmlMalloc allocates a part of memory to which temp2 also adresses.
When I compile the programm with these lines of code the fault doesn't

      String s = IntToStr(i_value);
      temp2 = (xmlChar *)s.c_str();
      nodePtr3 = xmlNewTextChild(NodePtr3, NULL, (xmlChar *)"value",

Has anyone an idea how I can eliminate this fault?

Yes, the code you show here will eliminate this fault, since the String object remains in scope. It should also work to use:

nodePtr3 = xmlNewTextChild(NodePtr3, NULL, (xmlChar *)"value", (xmlChar *)IntToStr(i_value).c_str());

Thomas Kutzer

Eric Zurcher
CSIRO Livestock Industries
Canberra, Australia
Eric Zurcher csiro au

[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]