Note that there are some explanatory texts on larger screens.

plurals
  1. PODoes this cause a memory leak? Allocating new objects in function call
    text
    copied!<p>The following code is taken from a DirectX tutorial and slightly modified by me:</p> <pre><code>void Initialize() { // case 1 m_camera.SetLookAt( new D3DXVECTOR3( x_component, y_component, z_component ) ); // case 2 m_camera.SetLookAt( &amp;D3DXVECTOR3( x_component, y_component, z_component ) ); // case 3 { m_camera.SetLookAt( &amp;D3DXVECTOR3( x_component, y_component, z_component ) ); } //more stuff to do here } void CCamera::SetLookAt( D3DXVECTOR3* pLookAt ) { m_lookAt.x = pLookAt-&gt;x; m_lookAt.y = pLookAt-&gt;y; m_lookAt.z = pLookAt-&gt;z; //delete pLookAt; // solution for case 1? } </code></pre> <p>m_camera is instance of class CCamera, which has a private member D3DXVECTOR3 m_lookAt. The SetLookAt() function takes a pointer to a D3DXVECTOR3. </p> <p>My question is, what is the difference between the ways this pointer is provided (case 1 and 2) ?</p> <p>As far as my understanding goes, in case 1, the D3DXVECTOR is allocated from heap. The created pointer is passed to SetLookAt(), which copies the data and quits. Then, Initialize() quits, without releasing the memory taken by the D3DXVECTOR, resulting in a memory leak. The possible solution would be to uncomment the last line in SetLookAt(). </p> <p>In case 2, D3DXVECTOR is allocated on stack and its adress is passed to SetLookAt. This time, the D3DXVECTOR is freed only when Initialize() is finished. </p> <p>Is my understanding correct? And what if I (in case 2) want the memory the D3DXVECTOR3 occupies to be freed as soon as the SetLookAt() function ends? Will wrapping the SetLookAt() in curly brackets (case 3) suffice to force the created D3DXVECTOR3 to be freed once SetLookAt is done?</p> <p>Also, would it make any difference if the call to SetLookAt() (in all 3 cases), the vector would be called using literal values, e.g. D3DXVECTOR3( 8.0f, 0.0f, 5.0f ) instead of D3DXVECTOR3( x_component, y_component, z_component ) ?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload