Question

I've a fairly complex application written in c++. I've a class called OrderBook. I need to create an array of OrderBook objects dynamically, so what i've done is,

OrderBook* pOrderBooks; // In header file

At runtime, I create the array as

p_OrderBooks = new OrderBook[n]; // n is an integer initialized at run time

The program works fine. But when I try to delete the array (as I need to create a new array pointed by pOrderBooks) the program crashes. This is how i delete it.

delete[] p_OrderBooks;

I've made sure that the crash happen exactly due to that line. So what i'm currently doing is reinitializing the pointer without deleting the previously allocated memory.

//delete[] p_OrderBooks; // <- crash happens here
p_OrderBooks = new OrderBook[k]; // for some 'k'

But it's bad since there'll be a memory leak. I'd like to know how to properly free the memory before re-pointing to the new array.

Was it helpful?

Solution 3

I found the issue. I'm passing a pointer to an object created in the base class to OrderBook objects.

Server* p_Server = new Server(); // Some class
...
pOrderbook[i]->SetServer(p_Server) // <- for i=[0:99]

Passed p_Server is stored in OrderBook objects as p_ServerBase (say).

Server* p_ServerBase; // <- in OrderBook.h
...
OrderBook::SetServer(Server* pServer)
{
    p_ServerBase = pServer;
}

Then in the OrderBook's distructor i'm trying to delete that, p_ServerBase, which is still being used in the base class.

...
~OrderBook()
{
    delete p_ServerBase;
}

Haven't had that experiance before. I' won't do that again :)

OTHER TIPS

You are allocating p_OrderBooks but deleting pOrderBooks

If that's just a simple typo in your post, then it is likely that you are overrunning the bounds of this array, writing to elements past the beginning or end, therefore corrupting the heap so it crashes when you try to delete it.

Is it possible that one or more of your destructors for OrderBook is throwing an exception out of the destructor? If so (typically considered bad) and if it is not handled will crash your application.

If you are doing something like this:

OrderBook* p_OrderBooks;

int n;

p_OrderBooks = new OrderBook[n]; // here n contains garbage

cin>>n

delete[] p_OrderBooks;

Here n can be any garbage value, we don't know its size ,and perhaps we start accessing memory that we don't own. It could be problematic. You should take input first

cin>>n

p_OrderBooks = new OrderBook[n];

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top