New stops my object working correctly - c++

I've had to completely rewrite this problem as I've found out a lot more about it now.
Background:
My programme is drawing some 3d objects under directx11. I have a class that contains the data, pointers, and functions needed to draw the required 3d objects. Everything was working well. I could create many different 3d objects and draw them wherever I wanted. Great!
Then I needed to put them in a container and into a vector so I didn't have to create each object manually, this was where the trouble started; it would crash 1 time in 5 or so.
Unhandled exception at 0x00C308C1 in SpritesNTextN3D.exe: 0xC0000005: Access violation reading location 0xFFFFFFFF.
It crashed when using vectors and maps. I continued this line of enquiry and tried using a pointer and new:
ThreeD_Cube* threed_cube_p;
threed_cube_p = new ThreeD_Cube;
This also caused it to crash when I ran its draw function.
threed_cube_p->draw(threeD, camera, d3dContext_mp);
However if created as a standard object:
ThreeD_Cube threed_cube_;
The draw function never crashes.
threed_cube_-.draw(threeD, camera, d3dContext_mp);
Likewise, creating a pointer to threed_cube_ works as expected.
Question:
What is new doing that the default constructor isn't. Is there anything I should be looking at to resolve this problem?

It seems you have a good constructor, but bad/insufficient (default) assignment operator and bad/insufficient (default) copy constructor.
Let's see why some parts of your code works but some not:
//threed_cube_vec[0].draw(threeD, camera, d3dContext_); // doesnt work!!!
It tells you what's in threed_cube_vec[0] is a bad/corrupted object.
ThreeD_Cube test = threed_cube_vec[0]; // But, if I copy it...
In this line, (for some reason) firstly the constructor is called, which gives you a good object. Then the "=" is called, partially the object is modified, but the object is still good since it was already good before the "="
ThreeD_Cube* test = &threed_cube_vec[0];
As for a pointer, it is the essentially object threed_cube_vec[0] itself, so still corrupted.
ThreeD_Cube test = threed_cube_vec[0];
vector<ThreeD_Cube> test2;
test2.push_back(test);
test2[0].draw(threeD, camera, d3dContext_);
This does not fixed the problem as you said. "test" is a good object, but when you push_back(test) into test2, a copy is pushed back [if you change it to test2.push_back(std::move(test) , the problem could be gone]. Since the copy constructor is incomplete, the object in test2[0] is corrupted. Similar scenario happens with your map.
Conclusion: if an object is originated from the constructor, you get a good object; if an object is originated from a copy constructor, it is corrupted.
A quick test you can do: resize your vector after you declare it, the error should be gone temporarily.

Crash after m = XMMatrixIdentity() - aligment memory in classes?
This topic covers the answer to my problem. I eventually tracked it down to XMMATRIX causing crashes with new due to memory alignment.
Here's a shortened version of the problem:
void matrix_test_pointer()
{
XMMATRIX* xmmatrix_p;
xmmatrix_p = new XMMATRIX;
*xmmatrix_p = XMMatrixIdentity(); // this is where it crashes
}
void matrix_test()
{
XMMATRIX xmmatrix;
xmmatrix = XMMatrixIdentity();
}
int main()
{
string wait;
matrix_test();
cout << "matrix_test() completed.\n";
matrix_test_pointer();
cout << "matrix_test_pointer() completed.\n"; // If it does you are lucky :)
cin >> wait;
return 0;
}
Chances are matrix_test will complete but it will crash before pointer will complete.

Related

Read Access Violation From Using Smart Pointers

This problem has bugged me for several days now, and I just cant figure it out. What I am trying to do is get an Entity from the entityMap and make a copy of it. An Entity is essentialy a map of components, so I looped through each component and made a copy of it. I debugged the program, and it worked fine until the very last line, where it said "read access violation this was 0xFFFFFFFFFFFFFFF7." It was very strange as everything was initialized (I checked the debugger)
if (entityMap.find(classname) != entityMap.end()) {
std::shared_ptr<Entity> & prefab = entityMap[classname];
std::shared_ptr<Entity> entity = std::shared_ptr<Entity>(new Entity());
for (auto & component : prefab->GetComponentMap()) {
Component * compPtr = component.second.get();
std::cout << compPtr->GetMemorySize() << "\n";
size_t size = sizeof(compPtr->GetMemorySize());
void * buffer = operator new(size);
memcpy(buffer, compPtr, size);
std::shared_ptr<Component> newComponent = std::shared_ptr<Component>(reinterpret_cast<Component *>(buffer));
entity->AddComponent(newComponent);
newComponent->SetOwner(entity);
}
Here is the offending line
newComponent->SetOwner(entity);
Here is all it does, setting the owner instance variable to the passed in parameter. That was where the debugger complained and sent me to file "memory" at _Decref method.
void Component::SetOwner(std::shared_ptr<Entity> owner) {
this->owner = owner;
}
The problem here is that you can’t copy objects just by copying the memory. For basic plain data objects without any constructors, destructors, or pointers this may work but for anything more complex it most likely won’t.
For example, if the object contains pointers to data and these are released in a destructor then the data is not deep copied, rather the pointer is, and you get double free and also possible pointers to unallocated memory. If the object relies on something being done in the constructor it is never done when copying memory. And depending on how the size is calculated it may not even be a complete copy.
This is why you should always provide a cloning mechanism in the class that takes care of these issues in a way that suits the object and makes sure there’s proper deep/shallow copying depending on the contents.

Access violation direct x update method

I have followed a dirextX 9 tutorial on utube and i have tried to modify the program to display multiple triangles based on a set of points. I am using it as a sort of plotter. in my testing i generate a list of points within my plotter class. the plotter class then generates 3 vertices to create a small triangle around the point. the points are then passed to the directx device.
i have moved the code that generates the polygons into my update method, as i need to update the polygon list with fresh polygons.
The code works, but every now and then it will crash with the following error message
Unhandled exception at 0x010F6AF1 in DX3DPlotTest.exe: 0xC0000005: Access violation reading location 0x00000000.
im shure that the problem is to do with the memcpy command being called over and over. i've tried deleting pVert but that creates its own error as pVert is never initiated.
hear is my update version
`
void TestApp::Update(float dt)
{
void *pVerts;
plotter=new Plotter(MaxPoints,0.01f);
float x,y;
for(ULONG i=0;i<MaxPoints;i++)
{
x= (float)(distribution(generator)-2.0f);
y= (float)(distribution(generator)-2.0f);
plotter->Plot(x,y);
}
m_pDevice3D->CreateVertexBuffer(
plotter->listContentCount*sizeof(VertexPositionColor),
0,VertexPositionColor::FVF,
D3DPOOL_MANAGED,
&VB,
NULL
);
//d3d vertex buffer VB
VB -> Lock(0,sizeof(VertexPositionColor)*plotter->listContentCount, (void**)&pVerts, 0);
memcpy(pVerts,plotter->m_pVertexList,sizeof(VertexPositionColor)*plotter->listContentCount);
VB -> Unlock();
}
`
please can someone help me understand how to fix this problem? if been fiddling around with it for hours. It does work, but for a limited amount of time.
Thanks all.
EDIT:
OK now im shure its do to wich recreating my plotter instance
`
Plotter::Plotter(UINT PointCount,float pointsize)
{
listSize = PointCount*3;
listContentCount = 0;
bufferContentCount = 0;
Polycount = 0;
m_pStdtri = new VertexPositionColor[3];
m_pVertexList = new VertexPositionColor[listSize];
m_pStdtri[0] = VertexPositionColor(0.0f ,1.0f*pointsize ,d3dColors::Red);
m_pStdtri[1] = VertexPositionColor(1.0f*pointsize , -1.0f*pointsize ,d3dColors::Lime);
m_pStdtri[2] = VertexPositionColor(-1.0f*pointsize , -1.0f*pointsize ,d3dColors::Red);
}
Plotter::~Plotter()
{
delete(m_pStdtri);
delete(m_pVertexList);
}
void Plotter::Plot(float x, float y)
{
Polycount++;
m_pVertexList[listContentCount]=VertexPositionColor(x+m_pStdtri[0].x, y+m_pStdtri[0].y,d3dColors::Red);
listContentCount++;
m_pVertexList[listContentCount]=VertexPositionColor(x+m_pStdtri[1].x, y+m_pStdtri[1].y,d3dColors::Lime);
listContentCount++;
m_pVertexList[listContentCount]=VertexPositionColor(x+m_pStdtri[2].x, y+m_pStdtri[2].y,d3dColors::Blue);
listContentCount++;
}
`
There are a couple of things that can be wrong here. The plotter object seems to be never disposed, but it is potentially possible that it's done elsewhere. What bothers me, however, is your calling of CreateVertexBuffer over and over again, presumably without ever releasing the resource that you're using. So basically what happens in my opinion is: in every frame, you create a new VertexBuffer. As the memory on your GPU runs low, the command fails eventually, which you don't detect and try to use the "created" buffer, which is not really created. You need to know, that the buffer is not destroyed, even if you delete the object which holds the VB variable. The CreateVertexBuffer command occupies resources on GPU so they need to be explicitly freed when no longer needed. But let's return to the point. This function fails at some point. So it results in a NULL pointer error. My suggestion would be to create the buffer just once and then only update it in each frame. But first, make sure if it is the case.

Feed a QList with another

hi i'm trying to send a QList as a parameter to another class but for some reason i got a read access violation...
CompareTimeChannel.h
class CompareTimeChannel : public IDataChannel
public:
// #brief The method used to receive the list
void setData(const QList< QSharedPointer<core::ITrackSection> > & sections);
// #brief The list
QList< QSharedPointer<core::ITrackSection> > _sections;
};
CompareTimeChannel.cpp
// #brief Empty constructor
CompareTimeChannel::CompareTimeChannel()
{
}
void CompareTimeChannel::setData(const QList< QSharedPointer<core::ITrackSection> > & sections)
{
//_sections = *new QList< QSharedPointer<core::ITrackSection> > ();
_sections.clear();
_sections.append(sections);
}
Running this code will throw Exception at 0x31cc78d, code: 0xc0000005: read access violation at: 0x4, flags=0x0 on _sections.clear();
I tried to initialize the list before (the commented line _sections = *new QList<...>) but the exception is thrown the same.
An answer would be very appreciated...
EDIT
Ok it's fixed!
First, like #AndreasT said, i had to initialize the default QList constructor.
Then, according to #10WaRRioR01 's answer, the issue comes from CompareTimeChannel which wasn't initialized the first time the method was called. Fixed using :
CompareTimeChannel* chan = static_cast<CompareTimeChannel*>(channel);
Q_ASSERT(chan);
if (chan) {
chan->setData(sections);
}
else {
qDebug() << "Dynamic cast failure";
}
Thank you all, guys!
//_sections = *new QList< QSharedPointer<core::ITrackSection> > ();
You shouldn't ever do something like this. This creates a new instance of QList on the heap and it will never be deleted, so you have a memory leak
You should have done
_sections = QList< QSharedPointer<core::ITrackSection> > ();
instead, and it would be legal. But the most simple way is to use a copy assignment like this
_sections = sections
The problem you got is most likely related to the data you have in _sections. Maybe you are calling your methods on a null CompareTimeChannel object
You should initialize sections in the constructor.
The commented line is just horribly wrong.
new constructs the List on the heap, then you dereference that with *new and the assignment implicitly calls the copy constructor of the new list on the Heap and copies that into the instance. The thing on the heap is still aruond though, so you just created a memory leak.
// #brief Empty constructor
CompareTimeChannel::CompareTimeChannel()
:_sections() // initialization default constructor.
{
}
Edit regarding the comment:
The QList.clear() method calls the destructors of every element of the list. At least one of your shared pointers seems not to be initialized correctly. If you need more info, please paste the code that puts stuff into _sections.
Edit Regarding the exception:
As I said the problem is most likely with the shared pointers not being set to anything interesting. When the SP gets destroyed it calls the destructor of its content, which must exist, otherwise it throws a read access violation, which would explain the symptoms.
This what you showed should work. Your problem is in some other place.
This kind of problems might be caused by many different mistakes, like: bad static_cast or bad c-style cast, break in binary compatibility when you are using dynamic libraries, write outside of table, problems with compiler cache (this happens is quite often so cure for that is below).
First what I would try to do:
make clean
qmake
make
This fixes such problem quite often. if i doesn't help you have to find other problems in your code.

Cocos2d-x: Crash when initiating TMXTiledMap from string

I'm having problems creating a tmx map from string input.
bool LevelManager::initLevel(int currentLevel)
{
const char* map;
try {
map = LevelManager::getLevel(currentLevel);
} catch (int) {
throw 1;
}
if(map != NULL){
CCLog("%s", map);
tileMap = CCTMXTiledMap::create(map);
tileMap->setAnchorPoint(ccp(0,0));
tileMap->setPosition(ccp(15,20));
this->addChild(tileMap, 5);
backgoundLayer = tileMap->layerNamed("Background");
} else {
throw 1;
}
return true;
}
Thats my code.
It is very unstable. Most of the times it crashes and sometimes it doesn't.
I'm loading my map from the string map. Wich is a const *char.
My map is named Level1.tmx and when i load the map like this: tileMap = CCTMXTiledMap::create("Level1.tmx"); it always works and never crashes.
And i know for a fact that the value of map is Level1.tmx because i log it in the line before the load.
When it crashes the log outputs this: (lldb)
and on the line tileMap->setAnchorPoint(ccp(0,0)); it says "Thread 1: EXC_BAD_ACCESS (code=2, adress=0x0)
Does anyone know why this happens and how to fix it?
Many thanks.
Ps: i'm using xcode, the latest cocos2d-x release and the iPhone simulator
Edit:
Using breakpoints i checked where things go bad while loading the tilemap.
on the line tileMap = CCTMXTiledMap::create(map);
my variable map is still fine
but on line tileMap->setAnchorPoint(ccp(0,0));
it is suddenly corrupted (most of the time)
It sounds like you're returning a char* string created on the stack, which means the memory may or may not be corrupted, depending on circumstances, moon phases, and what not.
So the question is: How is getLevel defined and what does it do (post the code)?
If you do something like this:
const char* LevelManager::getLevel(int level)
{
char* levelName = "default.tmx";
return levelName;
}
…then that's going to be the culprit. The levelName variable is created on the stack, no memory (on the heap) is allocated for it. The levelName variable and the memory it points to become invalid as soon as the method returns.
Hence when the method leaves this area of memory where levelName points to can be allocated by other parts of the program or other method's stack memory. Whatever is in that area of memory may still be the string, or it may be (partially) overridden by other bits and bytes.
PS: Your exception handling code is …. well it shows a lack of understanding what exception handling does, how to use it and especially when. I hope these are just remnants of trying to get to the bottom of the issue, otherwise get rid of it. I recommend reading a tutorial and introductions on C++ exception handling if you want to continue to use exceptions. Especially something like (map != NULL) should be an assertion, not an exception.
I fixed it.
const char* was to blame.
When returning my map as a char * it worked flawless.
const char *levelFileName = level.attribute("file").value();
char *levelChar = new char[strlen(levelFileName) + 1];
std:: strcpy (levelChar, levelFileName);
return levelChar;
Thats how i now return the map.

Pointer object in C++

I have a very simple class that looks as follows:
class CHeader
{
public:
CHeader();
~CHeader();
void SetCommand( const unsigned char cmd );
void SetFlag( const unsigned char flag );
public:
unsigned char iHeader[32];
};
void CHeader::SetCommand( const unsigned char cmd )
{
iHeader[0] = cmd;
}
void CHeader::SetFlag( const unsigned char flag )
{
iHeader[1] = flag;
}
Then, I have a method which takes a pointer to CHeader as input and looks
as follows:
void updateHeader(CHeader *Hdr)
{
unsigned char cmd = 'A';
unsigned char flag = 'B';
Hdr->SetCommand(cmd);
Hdr->SetFlag(flag);
...
}
Basically, this method simply sets some array values to a certain value.
Afterwards, I create then a pointer to an object of class CHeader and pass it to
the updateHeader function:
CHeader* hdr = new CHeader();
updateHeader(hdr);
In doing this, the program crashes as soon as it executes the Hdr->SetCommand(cmd)
line. Anyone sees the problem, any input would be really appreciated
When you run into a crash, act like a crime investigator: investigate the crime scene.
what is the information you get from your environment (access violation? any debug messages? what does the memory at *Hdr look like? ...)
Is the passed-in Hdr pointer valid?
Then use logical deduction, e.g.:
the dereferencing of Hdr causes an access violation
=> passed in Hdr points to invalid memory
=> either memory wasn't valid to start with (wrong pointer passed in), or memory was invalidated (object was deleted before passing in the pointer, or someone painted over the memory)
...
It's probably SEGFAULTing. Check the pointers.
After
your adding some source code
your comment that the thing runs on another machine
the fact that you use the term 'flag' and 'cmd' and some very small datatypes
making me assume the target machine is quite limited in capacity, I suggest testing the result of the new CHeader for validity: if the system runs out of resources, the resulting pointer will not refer to valid memory.
There is nothing wrong with the code you've provided.
Are you sure the pointer you've created is the same same address once you enter the 'updateHeader' function? Just to be sure, after new() note the address, fill the memory, sizeof(CHeader), with something you know is unique like 0XDEAD, then trace into the updateHeader function, making sure everything is equal.
Other than that, I wonder if it is an alignment issues. I know you're using 8 bit values, but try changing your array to unsigned ints or longs and see if you get the same issue. What architecture are you running this on?
Your code looks fine. The only potential issue I can see is that you have declared a CHeader constructor and destructor in your class, but do not show the implementation of either. I guess you have just omitted to show these, else the linker should have complained (if I duplicate this project in VC++6 it comes up with an 'unresolved external' error for the constructor. It should also have shown the same error for the destructor if you had a... delete hdr; ...statement in your code).
But it is actually not necessary to have an implementation for every method declared in a class unless the methods are actually going to get called (any unimplemented methods are simply ignored by the compiler/linker if never called). Of course, in the case of an object one of the constructor(s) has to be called when the object is instantiated - which is the reason the compiler will create a default constructor for you if you omit to add any constructors to your class. But it will be a serious error for your compiler to compile/link the above code without the implementation of your declared constructor, so I will really be surprised if this is the reason for your problem.
But the symptoms you describe definitely sounds like the 'hdr' pointer you are passing to the updateHeader function is invalid. The reason being that the 1st time you are dereferencing this pointer after the updateHeader function call is in the... Hdr->SetCommand(cmd); ...call (which you say crashes).
I can only think of 2 possible scenarios for this invalid pointer:
a.) You have some problem with your heap and the allocation of memory with the 'new' operator failed on creation of the 'hdr' object. Maybe you have insufficient heap space. On some embedded environments you may also need to provide 'custom' versions of the 'new' and 'delete' operator. The easiest way to check this (and you should always do) is to check the validity of the pointer after the allocation:
CHeader* hdr = new CHeader();
if(hdr) {
updateHeader(hdr);
}
else
//handle or throw exception...
The normal behaviour when 'new' fails should actually be to throw an exception - so the following code will cater for that as well:
try{
CHeader* hdr = new CHeader();
} catch(...) {
//handle or throw specific exception i.e. AfxThrowMemoryException() for MFC
}
if(hdr) {
updateHeader(hdr);
}
else
//handle or throw exception...
}
b.) You are using some older (possibly 16 bit and/or embedded) environment, where you may need to use a FAR pointer (which includes the SEGMENT address) for objects created on the heap.
I suspect that you will need to provide more details of your environment plus compiler to get any useful feedback on this problem.