Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Problems Deleting Arrays

Status
Not open for further replies.

Dolman

Programmer
Feb 3, 2002
8
GB
Hi, I am having problems deleting an array in my clear up code of a DirectX application in visual c++. The application runs fine until you exit it or the clean-up code is called for another reason.

The array is defended in the following way:

DWORD g_dwNumModels = 0L; //Used to store the number of used records in the array

typedef struct MODEL_STORAGE_SYSTEM{
D3DMATERIAL8* pMeshMaterials;
LPDIRECT3DTEXTURE8* pMeshTextures;
DWORD dwNumMaterials;
LPD3DXMESH pMesh;
} MSSSTORAGE;

MSSSTORAGE g_mssModels[100];

And I am attempting to delete it using the following method:

if( g_mssModels )
{
DWORD dwModelNumber;
for(dwModelNumber = 0; dwModelNumber < g_dwNumModels; dwModelNumber++)
{
g_mssModels[dwModelNumber].pMesh->Release();
for( DWORD i = 0; i < g_mssModels[dwModelNumber].dwNumMaterials; i++ )
{
if( g_mssModels[dwModelNumber].pMeshTextures )
g_mssModels[dwModelNumber].pMeshTextures->Release();
}
}
delete[] (void *)&g_mssModels;
}


Can any one suggest what I am doing wrong or how you would go about deleting the same array?

David
 
You declared your array on the stack as

Code:
MSSSTORAGE    g_mssModels[100];

You can't delete[] an array created on the stack. The easiest way to clean up such an array is:

1) Create a destructor (yes, structs can have member functions, including constructors and destructors) for your struct that releases the interface pointers.

2) Instead of declaring the array like this,

Code:
MSSSTORAGE    g_mssModels[100];

declare it like this:

Code:
MSSSTORAGE    *g_mssModels;

When the app starts up, you can say

Code:
g_mssModels=new MSSSTORAGE[100];

You can now delete[] this array. When you do, the destructor for each element will be called, and the interface pointers will be released. This also changes your cleanup code from that mess to the single line

Code:
delete [] g_mssModels;

Of course, now, if you clean up but don't exit, you need to reallocate the memory before you can reuse the array.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top