Hi I have a cross platform C++ app running on Fedora25 which is predictably crashing after a around a day of execution with an error realloc(): invalid next size.
I have narrowed the issue down to on particular pthread which sends out periodic updates to connected clients and empties the outgoing message queue. I am allocating space for char * inside functions called by the thread, which I free up after sending. I do not typically use C++ so I am doing std::string stuff in the backaround an then converting to char * when I need it. I want to make sure I am not missing something simple and any tips on how to re-structure or fix this.
static void* MyPThreadFunc(void * params) {
assert(params);
MyAppServer *pAppServer = (MyAppServer *)params;
if(pAppServer != NULL) {
int loopCounter = 1;
char* tempBuf;
int tempBufLen;
int tempDatSetDelay;
while(true) {
for(int i=0; i<pAppServer->GetUpdateDataSetCount();i++) {
tempDatSetDelay = pAppServer->GetDataSetDelay(pAppServer->VecDatSets[i].name);
if(tempDataSetDelay == 1 ||(tempDataSetDelay > 0 && loopCounter % tempDataSetDelay == 0)) {
pAppServer->UpdateDataSetMsgStr(pAppServer->VecDataSets[i]);
tempBuf = (char*)pAppServer->GetDataSetMsgStr(i); //returns const char*
broadcast(pAppServer->Con,mg_mk_str(tempBuf));
delete [] tempBuf;
}//if
} //for
//empty outgoing queue
tempBuf = pAppServer->OUtgoingMsgQueue.peek(tempMsgLen);
while(tempMsgLen>0) {
broadcast(pAppServer->Con,mg_mk_str(tempBuf));
pAppServer->OUtgoingMsgQueue.dequeue();
delete [] tempBuf;
tempBuf = pAppServer->OUtgoingMsgQueue.peek(tempMsgLen);
}
sleep(1);
loopCounter = loopCounter==std::numeric_limits<int>::max() ? 1 : ++loopCounter;
} //while
pAppServer=0;
}
}
const char* AppServer::GetDataSetMsgStr(const int idx) {
pthread_mutex_lock(&mLock);
// Dynamically allocate memory for the returned string
char* ptr = new char[VecDataSets[idx].curUpdateMsg.size() + 1]; // +1 for terminating NUL
// Copy source string in dynamically allocated string buffer
strcpy(ptr, VecDataSets[idx].curUpdateMsg.c_str());
pthread_mutex_unlock(&mLock);
// Return the pointer to the dynamically allocated buffer
return ptr;
}
char* MsgQueue::peek(int &len) {
char* myBuffer = new char[512];
len = 0;
pthread_mutex_lock(&mLock);
if(front==NULL) {
len = -1;
pthread_mutex_unlock(&mLock);
return myBuffer;
}
len = front->len;
strncpy(myBuffer,front->chars,len);
pthread_mutex_unlock(&mLock);
return myBuffer;
}