Easy to ignore: handling when ccomvariant. readfromstream fails

Source: Internet
Author: User

In serialization and deserialization, we often use ccomvariant. readfromstream to read variables from a data stream. RegularCodeAs follows:

Hresult _ pimshell_ajaxlist_load (istream * pstream) <br/>{< br/>... <br/> ccomvariant vvalue = (bool) True; <br/>... <br/> hresult hR = vvalue. readfromstream (pstream); <br/> If (failed (HR) <br/> return hr; <br/>... <br/>}< br/>

 

In general, this code can work well. But sometimes it causesProgram. What is the situation? Let's take a look:

 

Scenario: If pstream serializes a COM object, we need to read the COM Object to the ccomvariant variable vvalue.

1. Other values have been saved for vvalue. For example, vvalue. Vt = vt_bool; vvalue. boolval = variant_true;

2. Run vvalue. Clear () in readfromstream (). Vvalue. vt changes to vt_empty, and vvalue. boolval remains unchanged.

2. Read vartype in readfromstream. The vvalue. VT is vt_dispatch.

3. readfromstream reads the COM object again. In an accident, the vvalue. pdispval is not assigned, so it is still vvalue. boolval = variant_true.

4. When return HR, The vvalue destructor is automatically executed and vvalue. Clear () is called (). Because the current VT is equal to vt_dispatch

Vvalue. pdispval-> release (); in this case, vvalue. pdispval is neither a null pointer nor a valid interface pointer. This causes the program to crash.

 

Therefore, the more secure code should be like this:

Hresult _ pimshell_ajaxlist_load (istream * pstream) <br/>{< br/>... <br/> ccomvariant vvalue = (bool) True; <br/>... <br/> hresult hR = vvalue. readfromstream (pstream); <br/> If (failed (HR) <br/>{< br/> // *** important <br/> :: variantinit (& vvalue); <br/> return hr; <br/>}< br/>... <br/>}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.