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/>}