I'm writing a party system for a game, and I'm getting some very strange behavior out of a std::set std::wstring that contains IP addresses for the party. The error I'm getting is in xtree, usually in clear, but I've also hit it in insert. It's a read access violation at _Head->_Parent, usually says something like "_Head->_Parent was [memory address]."
This problem is very rare, and I've been trying to reproduce it for 2 months with no success. The game is up 24/7, and thousands of parties are created and destroyed each day, and I only get this error 2-3 times a week. Everything that inserts into, erases from, iterates over, or clears this set has a global mutex around it, that's only used for this set. Here's the relevant code:
Party.h
```
private:
std::set<std::wstring> ipList;
public:
std::set<std::wstring> getIPList() { return ipList; }
```
Party.cpp
```
PartyManager::DisbandParty(Party* party){
SAFE_DELETE(party);
}
Party::~Party(){
ipList.clear();
}
Party::AddPartyMember(){
getUniquePlayerLock.lock();
ipList.insert(s2ws(player->GetClientSession()->GetRemoteIP()));
getUniquePlayerLock.unlock();
}
Party::LeaveParty(){
getUniquePlayerLock.lock();
ipList.erase(s2ws(player->GetClientSession()->GetRemoteIP()));
getUniquePlayerLock.unlock();
}
Party::KickMember(){
getUniquePlayerLock.lock();
ipList.erase(s2ws(kickedplayer->GetClientSession()->GetRemoteIP()));
getUniquePlayerLock.unlock();
}
Party::GetUniquePlayers(){
std::set<std::wstring>::iterator it;
std::wstring curIP;
std::list<CPlayer*> uniquePlayers;
if (!ipList.empty()) {
for (it = ipList.begin(); it != ipList.end(); it++)
{
curIP = *it;
//std::wcout << "\nChecking IP " << curIP;
for (int i = 0; i < m_byMemberInfoCount; i++)
{
//std::cout << "\n" << i;
CPlayer* player = GetPlayer(i);
if (player) {
if (curIP == s2ws(player->GetClientSession()->GetRemoteIP())) {
uniquePlayers.push_back(player);
//std::wcout << "\n" << curIP;
break;
}
}
}
}
}
return uniquePlayers;
}
```
I'm all out of ideas here. It has to be some sort of undefined behavior, memory corruption, or something very obvious that I'm missing. Maybe in certain circumstances ipList is being destroyed before the party destructor is called? I'm still fuzzy on when variables declared in header files are considered "out of scope" and thus destroyed. Any help is appreciated.
Edit: With this logic, would the value of player->GetClientSession()->GetRemoteIP() be destroyed until it is repopulated?
Edit2: I've made some changes to check for nulls in the client session and IP as requested. This time, I'm getting an access violation error on accessing the lower bound of the set.
```
template <class _Keyty>
_Tree_find_result<_Nodeptr> _Find_lower_bound(const _Keyty& _Keyval) const {
const auto _Scary = _Get_scary();
_Tree_find_result<_Nodeptr> _Result{{_Scary->_Myhead->_Parent, _Tree_child::_Right}, _Scary->_Myhead}; **ACCESS VIOLATION ERROR IS HERE**
_Nodeptr _Trynode = _Result._Location._Parent;
while (!_Trynode->_Isnil) {`enter code here`
_Result._Location._Parent = _Trynode;
if (_DEBUG_LT_PRED(_Getcomp(), _Traits::_Kfn(_Trynode->_Myval), _Keyval)) {
_Result._Location._Child = _Tree_child::_Right;
_Trynode = _Trynode->_Right;
} else {
_Result._Location._Child = _Tree_child::_Left;
_Result._Bound = _Trynode;
_Trynode = _Trynode->_Left;
}
}
return _Result;
}
```
What could I possibly be doing to this set to cause this memory access error? It's a member variable being accessed in a class function, with no out of band destructors being called on it anywhere. I'm totally lost here.
Edit 3: Adding ifdefs for the global mutex below:
globalVariables.h:
#pragma once
#ifndef playerLockDefined
#include <mutex>
#define playerLockDefined
extern std::mutex getUniquePlayerLock;
#endif // !1
globalVariables.cpp:
#include "stdafx.h"
#include "globalVariables.h"
std::mutex getUniquePlayerLock;
Related
I have a method which loads OGRFeature's and extracts data from them.
However, when I call the method OGRFeature::DestroyFeature() to release the memory, I get a segmentation fault.
void Class::processFeatures() {
OGRFeature* feature;
feature = layer->GetNextFeature();
while( feature != NULL ) {
handleGeometries(); //Handling Geometries
doY(); //Handling Fields
OGRFeature::DestroyFeature(feature);
feature = layer->GetNextFeature();
}
}
void Class::handleGeometries() {
OGRGeometry* geometry = feature->GetGeometryRef();
//Some handling code
delete geometry;
}
The code runs and saves the information if I exclude the DestroyFeature. This example does work.
#include "gdal.h"
#include "gdal_priv.h"
#include <ogrsf_frmts.h>
int main()
{
GDALAllRegister();
GDALDataset* map;
map = (GDALDataset*) GDALOpenEx("shape.shp",GDAL_OF_VECTOR,NULL,NULL,NULL);
if (map)
{
OGRLayer* layer = map->GetLayer(0);
OGRFeature* feature;
feature = layer->GetNextFeature();
while( feature != NULL ) {
OGRFeature::DestroyFeature(feature);
feature = layer->GetNextFeature();
}
GDALClose(map);
}
return 0;
}
What is causing the problem? And how would I solve it?
EDIT: second example expanded
This answer comes after a series of comments/edits to the original question that lead to this conclusion:
Deleting the geometry pointer in the handleGeoemtry() method is what causes the memory violation when the DestroyFeature() function is called, as the geometry OGRFeature::GetGeometryRef() returns a reference to an object but does not transfer the ownership to the caller.
You can use the OGRFeature::StealGeoemtry to take the ownership, or simply remove the delete geometry instruction as the DestroyFeature() function will dispose of it anyway.
I have the following code which returns ERROR in many lines:
bool func()
{
if (acondition)
{
return 0;
}
return 1;
}
int cmdfun()
{
other_funcs;
if (func()) return ERROR#NUMBER;
other_funcs;
if (func()) return ERROR#NUMBER;
}
But I found its becoming longer and longer. How can I encapsulate return ERROR#NUMBER into func() also? Or any way to encapsulate if (func()) return ERROR; into another independent function?
You can't really achieve this using return on its own.
But you could throw an exception in func which will bubble up the call stack, in the way you seem to want program control to:
struct myexception{}; /*ToDo - inherit from std::exception?*/
bool func()
{
if (acondition){
return 0; /*normal behaviour, perhaps make `func` void if not needed?*/
}
throw myexception();
}
cmdfun then takes the form:
int cmdfun()
{
other_funcs;
func();
other_funcs;
func();
/* don't forget to return something*/
}
Finally, make sure you catch the exception in the caller to cmdfun.
As I said it is not an exception and cannot be handled by std::exception, it is just an error message and ERROR#NUMBER is just another macro. And I cannot access to the caller to cmdfun(). So unable to adopt the first answer. But after asked someone else, it is possible to encapsulate returns and save time when typing them, though it's not recommended, but in this particular case, I can use macro. A complete example is given below:
#include <iostream>
using namespace std;
#define CHECK_VEC(acondition)\
if(checkcondition(acondition)) return -1;
bool checkcondition(bool acondition)
{
if (acondition) return 1;
return 0;
}
int fun_called_by_main()
{
int a = 5 + 4;
bool acondition = a;
CHECK_VEC(acondition);
return 1;
}
int main()
{
int a = fun_called_by_main();
cout << a << endl;
cin.get();
return 0;
}
If I understood corectly your question, you are asking for an 'error reporter' for your own errors. There are 2 solutions for 2 separate cases:
Case 1 - you still want to use a return statement to make an 'error reporter':
To do this, you'll have to make another function or just learn how to use goto. However, you don't need to - your function returns a boolean(bool) - which means you only have 2 possible results: 0 (False) and 1 (True)
bool func()
{
if (acondition)
{
return (bool)0; // False (no error)
}
return (bool)1; // True (error)
// Note: I used (bool)0 and (bool)1 because it is
// more correct because your returning type is bool.
}
void errorcase(bool trueorfalse)
{
switch(trueorfalse)
{
case False:
... // your code (func() returned 0)
break;
default:
... // your code (func() returned 1)
break;
// Note that you will not need to check if an error occurred every time.
}
return;
}
int cmdfun()
{
... // your code
errorcase(func());
... // again - your code
return 0; // I suppouse that you will return 0...
}
But I think that the second case is more interesting (unfortunetly it is also preety hard to understand as a beginner and the first solution might be a lot easier for you):
Case 2 - you decided to do it somehow else - that's by learning throw and catch - I won't repeat the answer because it is already given: #Bathsheba answered preety good...
When try to run my program with up to 1 thread, it works fine for a while (some seconds or minutes) but finally get segmentation fault(core dumped) or double free(faststop ) error.
Here are the function which the threads run.
//used in the Function
[Added] typedef folly::ProducerConsumerQueue<std::string*> PcapTask;
struct s_EntryItem {
Columns* p_packet; //has some arbitrary method and variables
boost::mutex _mtx;
};
//_buffersConnection.wait_and_pop()
Data wait_and_pop() {
boost::mutex::scoped_lock lock(the_mutex);
while (the_queue.empty()) {
the_condition_variable.wait(lock);
}
Data popped_value = the_queue.front();
the_queue.pop();
return popped_value;
}
struct HandlerTask {
std::string year;
folly::ProducerConsumerQueue<std::string*> queue = NULL;
};
-----------------------------------------
//The function which threads run
void Connection() {
std::string datetime, year;
uint32_t srcIPNAT_num, srcIP_num;
std::string srcIP_str, srcIPNAT_str, srcIPNAT_str_hex;
int counter = 0;
while (true) {
//get new task
HandlerTask* handlerTask = _buffersConnection.wait_and_pop();
PcapTask* pcapTask = handlerTask->queue;
year = handlerTask->year;
counter = 0;
do {
pcapTask->popFront();
s_EntryItem* entryItem = searchIPTable(srcIP_num);
entryItem->_mtx.lock();
if (entryItem->p_packet == NULL) {
Columns* newColumn = new Columns();
newColumn->initConnection(srcIPNAT_str, srcIP_str, datetime, srcIP_num);
entryItem->p_packet = newColumn;
addToSequanceList(newColumn);
} else {
bool added = entryItem->p_packet->addPublicAddress(srcIPNAT_str_hex, datetime);
if (added == false) {
removeFromSequanceList(entryItem->p_packet);
_bufferManager->addTask(entryItem->p_packet);
Columns* newColumn = new Columns();
newColumn->initConnection(srcIPNAT_str, srcIP_str, datetime, srcIP_num);
//add to ip table
entryItem->p_packet = newColumn;
addToSequanceList(newColumn);
}
}
entryItem->_mtx.unlock();
++_totalConnectionReceived;
} while (true);
delete pcapTask;
delete handlerTask;
}
}
You can use Valgrind, its very easy. Build your app in debug config and pass program executable to valgrind. It can tell you wide spectre of programming errors occuring in your app in runtime. The price of using Valgrind is that program runs considerably slower (some times tens times slower) than without Valgrind. Specically, for example, Valgrind will tell you where your your programs' memory was free'ed first when it tried to free it second time when it happens.
I'm not sure that it's the problem, but...
Are you sure that you must call delete over pcapTask?
I mean: you delete it but queue in struct HandlerTask is a class member, not a pointer to a class.
Suggestion: try to comment the line
delete pcapTask;
at the end of Connection()
--- EDIT ---
Looking at you added typedef, I confirm that (if I'm not wrong) there is something strange in your code.
pcapTask is defined as a PcapTask pointer, that is a folly::ProducerConsumerQueue<std::string*> pointer; you initialize it with a folly::ProducerConsumerQueue<std::string*> (not pointer)
I'm surprised that you can compile your code.
I think you should, first of all, resolve this antinomy.
p.s.: sorry for my bad English.
so I'm used to coding in C# and have just started using C++ again after a pretty substantial break. Essentially what I'm trying to do is to create a program that has lists of students with IDs, in courses.
I have this code that essentially prints out all available students in courses.
auto allCourses = WSUCourse::getAllCourses();
std::for_each(
allCourses.begin(),
allCourses.end(),
GetCoursePrinter());
The GetCoursePrinter() is called in this code in the constructor
struct GetCoursePrinter
{
void operator () (
MyCourse *coursePtr
)
{
std::cout << coursePtr->getIdentifier() <<
": " <<
coursePtr->getTitle() <<
std::endl;
}
};
My problem is after I delete an enrollment like so
MyEnrollment *enrollmentPtr = MyEnrollment::findEnrollment(
MyStudent::getStudentWithUniqueID(1000002),
MyCourse::getCourseWithIdentifier("CS 2800")
);
delete enrollmentPtr;
And then try to print it with GetCoursePrinter it crashes. I believe this is because it's trying to access something that doesn't exist. What I'm wondering is if there is a way to call something like this
if (allCourses.current() != null)
{
GetCoursePrinter();
}
else
{
//do nothing
}
when you call:
delete enrollmentPtr;
you need to remove this item in environment.
I have a custom string class that malloc/realloc/free's internally; For certain strings appending works fine, but on certain others it will always fail (small or large allocations). The same code worked fine on a different project, although it was an ANSI build.
I believe I'm implementing this correctly, but most likely I've overlooked something. The error occurs when I attempt to utilize the "szLog" buffer once the log has been opened. This simply contains the path to the program files directory (40 characters total). Using this same buffer without the "Log file '" prefix works fine, so it's an issue with the realloc section. And yes, the log does open properly.
I get 0xC0000005: Access violation reading location 0x00660063. only when realloc is used (but as previously stated, it doesn't always fail - in this situation, when szLog is input - but other variable strings/buffers do it too).
HeapReAlloc is the failing function inside realloc.c, errno being 22.
I've stripped the comments to try and keep the post as small as possible! Any help would be much appreciated.
gData.szLogStr is a UString, IsNull is a definition for "x == NULL" and unichar is simply a typedef for wchar_t
class UString : public Object
{
private:
unichar* mpsz;
unichar* mpszPrev;
UINT muiAlloc;
UINT muiLen;
public:
... other functions ...
UString& operator << (const unichar* pszAdd)
{
if ( IsNull(pszAdd) )
return (*this);
if ( IsNull(mpsz) )
{
muiAlloc = ((str_length(pszAdd)+1) * sizeof(unichar));
if ( IsNull((mpsz = static_cast<unichar*>(malloc(muiAlloc)))) )
{
SETLASTERROR(ERR_NOT_ENOUGH_MEMORY);
muiAlloc = 0;
return (*this);
}
mpszPrev = mpsz;
muiLen = str_copy(mpsz, pszAdd, muiAlloc);
}
else
{
UINT uiNewAlloc = (muiAlloc + (str_length(pszAdd) * sizeof(unichar)));
if ( muiAlloc < uiNewAlloc )
{
uiNewAlloc *= 2;
/* Fails */
if ( IsNull((mpsz = static_cast<unichar*>(realloc(mpsz, uiNewAlloc)))) )
{
SETLASTERROR(ERR_NOT_ENOUGH_MEMORY);
mpsz = mpszPrev;
return (*this);
}
mpszPrev = mpsz;
muiAlloc = uiNewAlloc;
}
muiLen = str_append(mpsz, pszAdd, muiAlloc);
}
return (*this);
}
and this being called from within main via:
UString szConf;
unichar szLog[MAX_LEN_GENERIC];
szConf << ppszCmdline[0];
szConf.replace(_T(".exe"), _T(".cfg"));
if ( GetPrivateProfileString(_T("Application"), _T("LogFile"), NULL, szLog, sizeofbuf(szLog), szConf.str()) == 0 )
{
UINT uiLen = str_copy(szLog, szConf.str(), sizeofbuf(szLog));
szLog[uiLen-3] = 'l';
szLog[uiLen-2] = 'o';
szLog[uiLen-1] = 'g';
}
if ( ApplicationLog::Instance().Open(szLog, CREATE_ALWAYS) )
{
gData.szLogStr.clear();
/* Erroring call */
gData.szLogStr << _T("Log file '") << szLog << _T("' opened");
APP_LOG(LL_WriteAlways, NULL, gData.szLogStr);
ObjMgr::Instance().DumpObjects(LogDumpedObjects);
}
You are programming in c++, so use new and delete. To 'renew', allocate a new memory area large enough to hold the new string, initialize it with the correct values and then delete the old string.
What is str_length() returning when it fails? I'd trace the value of muiAlloc and see what you're actually trying to allocate. It may not be a sane number.
Are you certain that whatever's in szLog is null-terminated, and that the buffer has room for whatever you're copying into it? It's not clear if str_copy is safe or not. It may be a wrapper around strncpy(), which does not guarantee a null terminator, but some people mistakenly assume it does.