void ServerManager::addWork(SocketClient *clientSocket, vector<char> data){
Work *work = new Work(clientSocket, data);
m_workHandler->addWork(work);
}
Here I created Work instance and hand the work to the WorkHandler.
m_workHandler->addWork(work);
This code is inserting the work into the queue.
This is one part of my server and if I run this code for long time then the server crashes with error saying like this
what() std::bad_alloc
I looked online and it is an error message that show there isn’t memory space available. So I realized I didn’t free the work object after I am done with using it.
So I was wondering where I should free the work object.
void ServerManager::addWork(SocketClient *clientSocket, vector<char> data){
Work *work = new Work(clientSocket, data);
m_workHandler->addWork(work);
delete work;
}
Can I do this? If I pass the work instance then it increases the reference count?
void WorkHandler::workLoop(){
printf("WorkHandler::workLoop, called\n");
while(m_workHandlerRun){
Work *work = getWork();
char *pdata = work->getVPointer();
unsigned char type = pdata[0];
printf("WorkHandler::workLoop, type %d\n", type);
Packet *packet = m_packetFactory->createInstance(static_cast<PACKET_TYPES>(type));
packet->fromByte(pdata);
delete work;
}
}
This is the code I handle the work….Should I delete work instance here or both place? Thanks in advance…
Judging by your second bit of code, it looks like the memory leak might actually be from the
Packetallocation, because theWorkinstance is being deleted in what seems like a correct place (inworkLoop, notaddWork). But I can’t be certain without seeing more of your code.Allocations in C++ don’t have a reference count, so you should delete the
Workinstance when you’re done using it. If you delete it beforehand, it’s gone: use that pointer and the results will be undefined (might work, probably won’t). If you don’t delete it, it will leak (as you can see).You should refactor your code to use smart pointers — look at std::unique_ptr<> and std::shared_ptr<> (or boost::scoped_ptr<> and boost::shared_ptr<>). They will help ensure things get deleted when they really should be: