Reading an XML Document Using a Limiting IMalloc Implementation

This topic illustrates how to implement an XmlLite application that controls the reader memory allocation. The reader memory allocation must be controlled to reduce denial of service threats where there is a risk of documents being uploaded that may consume large amounts of memory. A document can consume large amounts of memory in scenarios such as the following:

  • The document contains many nested elements.

  • The document contains an element with many attributes.

  • The document contains an element that has a very long name.

This example includes the following file:

To create the example

  1. Create a Visual Studio 2005 project. For more information about how to create an XmlLite application, see Building XmlLite Applications.

  2. Copy the content of Source: XmlLiteLimitedReader.cpp into your C++ source file.

  3. Build the example. This creates the debug directory that is required in the next step.

  4. Create an XML document by using Visual Studio 2005 or your favorite editor. To generate an E_OUTOFMEMORY error, the document should contain one or more of the following: many nested elements; an element that has many attributes; an element that has a very long name. Copy the document to the debug directory.

  5. Run the sample.

The following is the detailed list of what you have to do to implement an XmlLite application that controls the reader memory allocation:

  • Implement a class that extends the IMalloc interface. Implementing IMalloc lets you control the memory allocations of the reader. The IMalloc interface provides the Alloc method. The reader calls this method every time it has to allocate memory. The first call is from the CreateXmlReader method to allocate the reader object itself. Subsequent calls can be from any method on the reader.

  • Create an instance of the class that implements the IMalloc interface:

    Malloc* pMalloc = Malloc();
  • Use the CreateXmlReader method to instantiate your XmlLite reader and provide pMalloc as a parameter to the reader. If no IMalloc is provided, the default implementation of IMalloc is used. The following example shows how to pass pMalloc to the reader:

    if (FAILED(hr = CreateXmlReader(__uuidof(IXmlReader),(void**) &pReader, pMalloc)))
        wprintf(L"Error creating xml reader, error is %08.8lx", hr);
        return -1;
  • Be sure to check for the E_OUTOFMEMORY error. The reader will fail with E_OUTOFMEMORY error if the document that is being parsed exceeds the size allocated for the reader.

  • When you are done using pMalloc, release it: