Removing a rigid body, but still getting collisions for it - c++

What is the correct way to remove a rigid body, I am doing just this to remove it:
void removeRigidBody(btDynamicsWorld* pDynamicsWorld, btRigidBody* rb)
{
pDynamicsWorld->removeRigidBody(rb);
delete rb->getMotionState();
delete rb;
}
However, the object still appears in pDynamicsWorld->getCollisionObjectArray() after I do a pDynamicsWorld->stepSimulation
Strangely enough this does not happen on ARM, just x86.

Actually, this is what I've found. Posting code in the comments would look awful, that's why the answer instead.
//remove the rigidbodies from the dynamics world and delete them
int i;
for (i=m_dynamicsWorld->getNumCollisionObjects()-1; i>=0 ;i--)
{
btCollisionObject* obj = m_dynamicsWorld->getCollisionObjectArray()[i];
m_dynamicsWorld->removeCollisionObject( obj );
delete obj;
}
So you remove the body from the collision objects.

This was, like most bugs just a stupid mistake. Sorry to those who took time to read it.
The error was actually in some java that called the removeRigidBody by jni.
if (body.id > 0) {
The id is actually an int cast of the btRigidBody address, so of course any != 0 integer could be a valid address. On the x86, the addresses happened to be < 0 which on the other device happened to be > 0.

Related

RapidXML accessing sibling nodes causes segfaults for seemingly no reason

So I recently got a hold of RapidXML to use as a way to parse XML in my program, I have mainly been using it as a way to mess around but I have been getting some very weird issues that I'm really struggling to track down. Try and stick with me through this, because I was pretty thorough with trying to fix this issue, but I must be missing something.
First off here's the XML:
<?xml version="1.0" encoding="utf-8" ?>
<resources>
<image key="tilemap_roguelikesheet" path="res/media/tilemaps/roguelikesheet.png" />
<image key="tilemap_tiles" path="res/media/tilemaps/tiles.png" />
</resources>
The function the segfault occurs:
void TextureManager::LoadResource(const char* pathToFile)
{
rapidxml::xml_document<>* resource = Resources::LoadResource(pathToFile);
std::string imgName;
std::string imgPath;
if (resource != NULL)
{
rapidxml::xml_node<>* resourcesNode = resource->first_node("resources");
if (resourcesNode != NULL)
{
for (rapidxml::xml_node<>* child = resourcesNode->first_node("image"); child; child = child->next_sibling())
{
//Crash here on the second loop through.
imgName = child->first_attribute("key")->value();
imgPath = child->first_attribute("path")->value();
Astraeus::Log(moduleName, "Image Name: " + imgName);
Astraeus::Log(moduleName, "Image Path: " + imgPath);
TextureManager::AddTexture(imgName, imgPath);
}
}
else
{
Astraeus::Error(moduleName, "Resources node failed to load!");
}
resource->clear();
}
else
{
std::string fileName(pathToFile);
Astraeus::Error(moduleName, fileName + " could not be loaded.");
}
}
So segfault happens on the second loop of the for loop to go through all the nodes, and triggers when it tries to do the imgName assignment. Here's where things get a bit odd. When doing a debug of the program, the initial child nodes breakdown shows it has memory pointers to the next nodes and it's elements/attributes etc. When investigating those nodes, you can see that the values exist and rapidxml has seemingly successfully parsed the file.
However, when the second loop occurs, child is shown to still have the exact same memory pointers, but this time the breakdown in values show they are essentially NULL values, so the program fails and we get the code 139. If you try and look at the previous node, that we have just come from the values are also NULL.
Now say, I comment out the line that calls on the AddTexture function, the node is able to print out all the nodes values no problems at all. (The Log method is essentially just printing to console until I do some more funky stuff with it.) so the problem must lie in the function? Here it is:
void TextureManager::AddTexture(const std::string name, const std::string path)
{
Astraeus::Log(moduleName, "Loading texture: " + path);
if (texturesLookup.find(name) != texturesLookup.end())
{
Astraeus::Error(moduleName, "Texture Key: " + name + " already exists in map!");
}
else
{
texturesLookup.insert(std::make_pair(name, path));
//Texture* texture = new Texture();
/*if (texture->LoadFromFile(path))
{
//textures.insert(std::make_pair(name, texture));
}
else
{
Astraeus::Error(moduleName, "Failed to add texture " + name + " to TextureManager!");
}*/
}
}
Ignoring the fact that strings are passed through and so should not affect the nodes in any way, this function is still a bit iffy. If I comment out everything it can work, but sometimes just crashes out again. Some of the code got commented out because instead of directly adding the key name, plus a memory pointer to a texture, I switched to storing the key and path strings, then I could just load the texture in memory later on as a workaround. This solution worked for a little bit, but sure enough began to segfault all over again.
I can't really reliably replicate or narrow down what causes the issue everytime, so would appreciate any help. Is RapidXML doc somehow going out of scope or something and being deleted?
For the record the class is practically just static along with the map that stores the texture pointers.
Thanks!
So for anybody coming back again in the future here's what was happening.
Yes, it was a scope issue but not for the xml_document as I kept initially thinking. The xml_file variable that was in the resources load function was going out of scope, which meant due to the way RapidXML stores things in memory, as soon as that goes out of scope then it frees up the memory, which led to the next time dynamic allocation happened by a specific function it would screw up the xml document and fill it with garbage data.
So I guess the best idea is to make sure xml_file and xml_document do not go out of scope. I have added some of the suggestions from previous answers, but I will point out those items WERE in the code, before being removed to help with the debug process.
Thanks everybody for the help/advice.
I'm not sure, but I think that Martin Honnen made the point.
If next_sibling() return the pointer to the text node between the two "image" elements, when you write
imgName = child->first_attribute("key")->value();
you obtain that child->first_attribute("key") is a null pointer, so the ->value() is dereferencing a null pointer. Crash!
I suppose you should get the next_sibling("image") element; something like
for (rapidxml::xml_node<>* child = resourcesNode->first_node("image");
child;
child = child->next_sibling("image"))
And to be sure not to use a null pointer, I strongly suggest you to check the attribute pointers (are you really sure that "image" elements ever carry the "key" and the "path" elements?); something like this
if ( child->first_attribute("key") )
imgName = child->first_attribute("key")->value();
else
; // do something
if ( child->first_attribute("path") )
imgPath = child->first_attribute("path")->value();
else
; // do something
p.s.: sorry for my bad English.
This line is setting my teeth on edge...
rapidxml::xml_document<>* resource = Resources::LoadResource(pathToFile);
LoadResource returns a pointer, but you never free it anywhere...?
Are you 100% sure that function isn't returning a pointer to an object that's now gone out of scope. Like this classic bug...
int * buggy()
{
int i= 42;
return &i; // UB
}
As #max66 says. You should use next_sibling("image"). If that's failing, you need to find out why.

How could this address access violation?

Currently, there is one exception thrown from program written by C++, and running under windows.
here is the min dump information in the logs.
08/12/15 04:37:19 I New Information for UID 2d936a, FloorLoc F1505
08/12/15 04:37:19 E >>>>> EXCEPTION: Access Violation while trying to read address 20203567
[Fault address: 004AF945 01:000AE945 C:\Program Files (x86)\MySystems\WPR.exe 00400000] <<<<<
Call stack:
Load addr Address Frame Logical addr Module
00400000 004AF945 0588F8CC 0001:000AE945 C:\Program Files (x86)\MySystems\WPR.exe
00400000 004A89A4 0588FAEC 0001:000A79A4 C:\Program Files (x86)\MySystems\WPR.exe
According to the logical addr and .map file, I can find the codes where this exception thrown.
if (TempMSE->m_elem == NULL)
{
TempMSE->m_elem = new Element(element);
TempMSE->m_elem->SetLocation(FloorLoc);
LoggerInfo("New Information for UID %x, FloorLoc %s", Id, FloorLoc.ToString(buf));
}
TempMSE->m_elem->SetValue0(CIN_0, 0); // this exception is thrown here!!! through logical address 0001:000AE945
It seems that the m_elem gets one address from new operator, and there is NO exception for SetLocation function calling. Also the following log output correctly.
Why there is one exception thrown from SetValue0? Here is function SetValue0
void SetValue0(INDEX idx, DWORD val)
{
if (idx >= 0 && idx < MAX_INDEX){
if(val != m_Info[idx])
{
m_Info[idx] = val;
}
}
}
The m_Info is one array variable in the Element, and its size is MAX_INDEX.
On the other side, the address 0x20203567 seems one readable address, how could it be read violation?
Edit
Add more information here
class Element {
// other function here...
private:
FloorLocation m_FloorLoc;
DWORD m_Info[MAX_INDEX];
bool m_Dirty;
};
Element::Element(const Element& elem) {
m_FloorLoc = elem.m_FloorLoc;
for (int i = 0; i < MAX_INDEX; ++i)
m_Info[i] = elem.m_Info[i];
m_Dirty = elem.m_Dirty;
}
class FloorLocation {
// other function here...
private:
FloorId m_floorloc;
};
FloorLocation::FloorLocation( const FloorLocation& loc )
{
memset(&m_floorloc, ' ', 8); // space filled
if(loc.m_floorloc.id[0] != 0)
{
memcpy(m_floorloc.id, loc.m_floorloc.id, 8);
// eliminate nulls
for(int ndx=0; ndx < 8; ndx++)
{
if(m_floorloc.id[ndx] == 0)
m_floorloc.id[ndx]=' ';
}
}
}
typedef struct {
char id[8];
} FloorId;
These kinds of questions are a little hard to answer. I gave some ideas in comments, which I'll elaborate on here. Here are the kinds of things I look for when I have these sorts of crash logs with no other leads.
An access violation on read at that location suggests one of the following:
TempMSE is not a valid pointer, and the exception is thrown when attempting to get m_elem from it;
TempMSE->m_elem is not valid, and the exception is thrown inside SetValue0 when attempting to test the value of m_Info[idx].
In the latter case, this could occur if you delete TempMSE->m_elem somewhere but don't set it to NULL. If another thread is responsible for that delete, perhaps you have a race condition here where it's about to be set to NULL, but this code is executed first.
Another possibility is that either TempMSE or TempMSE->m_elem get corrupted somewhere along the way. This could be the result of a buffer overrun inside TempMSE (if you have arrays), or basically any sort of undefined behaviour that occurs near these pointers in memory. If TempMSE is on the stack, then look for any potential trouble there.
I don't want to fill this answer with other kinds of speculation (like heap corruption), but hopefully it gives you some avenues to try. The basic list of common culprits is this:
coding error (not initialising or resetting a value)
threading issues, race conditions...
undefined behaviour or overruns trashing data
Good luck!
I can't say what is actually wrong, but I would disassemble the code at 0x004AF945 - and several instructions before, and try to understand what part of the failing function that is.
As pointed out in one of the comments, the address that the fault happens at is suspiciously looking like 'C# ', which makes me think that somewhere a string is overflowing somewhere...
This is just a guess, but I suspect TempMSE->m_elem is what contains the value 0x20203567, and thus is NOT NULL when it tries to access it, meaning no logging is performed. [Obviously this is based on what code you have shown so far, and if there is logging before/after that show this is not the case, my second guess is that m_info is somehow wrong...

C++ segfault at the end of a for loop

This code is segfaulting and I can't really figure out why. When I use gdb it segfaults at the end of the function (the curly brace). So that doesn't really give me a lot of information as to what's going on. Here's the code, I'll provide extra info if needed.
typedef std::list<Ground> l_Ground;
void Player::y_collisions(l_Ground grounds) {
for (l_Ground::const_iterator ent = grounds.begin(); ent != grounds.end(); ent++) {
if (getGlobalBounds().intersects(ent->getGlobalBounds())) {
in_air = false;
velocity -= gravity;
}
}
}
EDIT: Upon closer inspection, it's probably segfaulting at the end of that for loop. Which still doesn't really make sense because of the way the for loop is written. It shouldn't go beyond the end of the list.
EDIT2: This will work because of the answer below.
typedef std::list<Ground> l_Ground;
void Player::y_collisions(const l_Ground& grounds) {
for (l_Ground::const_iterator ent = grounds.begin(); ent != grounds.end(); ent++) {
if (getGlobalBounds().intersects(ent->getGlobalBounds())) {
in_air = false;
velocity -= gravity;
}
}
}
You were passing the grounds parameter by value. That means a copy of the list was made. Apparently your Ground class have a broken copy constructor, which makes the getGlobalBounds() method referring to some invalid pointer, which caused the crash.
You should almost never pass a big object by value unless you want to immediately copy it. Always train yourself to type const & all the time :).

Replacing delete in C++, missinformation

I'm trying to (and have solved) a problem with 16 byte alignment issues with a class that contains SSE optimised members. But what is bugging me is a large portion of the examples I have found online contain a line of code that to me seems totally redundant yet is repeated in many places.
public:
void* operator new (size_t size)throw (std::bad_alloc)
{
void * p = _aligned_malloc(size, 16);
if (p == 0) throw std::bad_alloc();
return p;
}
void operator delete (void *p)
{
Camera* pC = static_cast<Camera*>(p);
_aligned_free(p);
}
The line in question is
Camera* pC = static_cast<Camera*>(p);
As pC is never referenced and goes out of scope at the end of the function, what is the point of doing it? I have tried taking the line out and it appears to make no difference at all yet that line appears in lots of examples! Am I missing something really obvious or has an anomalous line of code been copied from example to example blindly and become prevalent across a lot of "tutorials"?
The object ends its lifetime as soon as the destructor is entered, so you cannot do much with this pointer. The line Camera* pC = static_cast<Camera*>(p); can be removed safely and the only reason it exists in tutorials is that many people just copy-n-paste the code here and there without actually thinking how it works.
The clean and correct code for your delete() will look as follows:
void operator delete (void *p)
{
_aligned_free(p);
}
As discussed in many comments to your question, the following line is indeed redundant:
Camera* pC = static_cast<Camera*>(p); // Just an unused variable
Even if the p was of type Camera* before (other possibilities are the subclasses like Canon*, Sony*, Nikon*), you still cannot do much with pC, because the Camera::~Camera() should have already been called. operator delete is called after that.
P.S.: I haven't come across such practice to cast a pointer to specific class, but if you encounter such advise in a tutorial then you may want to change it.

Why I am getting a Heap Corruption Error?

I am new to C++. I am getting HEAP CORRUPTION ERROR. Any help will be highly appreciated. Below is my code
class CEntity
{
//some member variables
CEntity(string section1,string section2);
CEntity();
virtual ~CEntity();
//pure virtual function ..
virtual CEntity* create()const = 0;
};
I derive CLine from CEntity as below
class CLine:public CEntity
{
// Again some variables ...
// Constructor and destructor
CLine(string section1,string section2);
CLine();
~CLine();
CLine* Create() const;
}
// CLine Implementation
CLine::CLine(string section1,string section2) : CEntity(section1,section2){};
CLine::CLine();
CLine* CLine::create() const {return new CLine();}
I have another class CReader which uses CLine object and populates it in a multimap as below
class CReader
{
public:
CReader();
~CReader();
multimap<int,CEntity*>m_data_vs_entity;
};
//CReader Implementation
CReader::CReader()
{
m_data_vs_entity.clear();
};
CReader::~CReader()
{
multimap<int,CEntity*>::iterator iter;
for(iter = m_data_vs_entity.begin();iter!=m_data_vs_entity.end();iter++)
{
CEntity* current_entity = iter->second;
if(current_entity)
delete current_entity;
}
m_data_vs_entity.clear();
}
I am reading the data from a file and then populating the CLine Class.The map gets populated in a function of CReader class. Since CEntity has a virtual destructor, I hope the piece of code in CReader's destructor should work. In fact, it does work for small files but I get HEAP CORRUPTION ERROR while working with bigger files. If there is something fundamentally wrong, then, please help me find it, as I have been scratching my head for quit some time now.
Thanks in advance and awaiting reply,
Regards,
Atul
Continued from Y'day :
Further studying this in detail I now have realized that Heap allocation error in my case is because I am allocating something, and then overwriting it with a higher size.
Below is the code where in my data gets populated in the constructor.
CEntity::CEntity(string section1,string section2)
{
size_t length;
char buffer[9];
//Entity Type Number
length = section1.copy(buffer,8,0);
buffer[length]='\0';
m_entity_type = atoi(buffer);
//Parameter Data Count
length = section1.copy(buffer,8,8);
buffer[length]='\0';
m_param_data_pointer = atoi(buffer);
//.... like wise ....
}
I am getting the values at a fixed interval of 8 chars and I am adding a '\0' so this, i guess will take care of any garbage value that I encounter.
About
Heap allocation error: after normal block (XXX) at XXX, CRT detected that application wrote to memory after end of Heap buffer. Mostly, Heap allocation errors occur somewhere else than where it crashes. I would appreciate if some one here would help me, how to make use of this normal block and the address.
Thanks,
Well, you're only showing half the problem.
Where's the code that creates the CLine objects and stores them in the CReader?
Also, what do you consider actually "owns" the CEntity objects? Generally, you should make the 'owner' responsible for creation as well as deletion...
I wrote earlier:
"You might like to consider storing
the CEntitys directly in the map,
rather than storing pointers.
Potentially less efficient, but also
much less scope for cockups."
As Neil points out, it's not CEntities that you will be storing, so that suggestion isn't going to help you much...
Finally, after two days of debugging, I was able to fix up the crash. It was due to me copying wrong number of characters from the string.
Lessons learnt :
1. When you encounter memory allocation errors, try to form a simple test case which has minimum entities to reproduce the problem.
2. A sure shot way is a line by line debugging. I agree,it test your patience, but then, there are no short cuts to success
3. And it gives you a chance to do a code review, further enhancing the quality of code that you produce in future
Thank you for all your help and formatting my code :)
Regards,
Atul