开发者

NULL pointer comparison fails

I'm initializing in a class a pointer to be NULL. Afterwards I check if it is NULL in the same class. But it's not always 0x0. Sometimes it's 0x8 or 0xfeffffff or 0x3f800000 or 0x80 or other strange stuff. In most case the pointer is 0x0 but sometimes it gets altered somehow.

I'm sure that I'm not changing it anywhere in my code. Is there a 开发者_如何学JAVAway it gets changed by "itself"?

Here's my code:

MeshObject::MeshObject()
{
    mesh.vertexColors = NULL;
}

MeshObject::MeshObject(const MeshObject &_copyFromMe)
{
    SimpleLog("vertexColors pointer: %p", _copyFromMe.mesh.vertexColors);
    if (_copyFromMe.mesh.vertexColors != NULL)
    {
        SimpleLog("vertexColors");
        this->mesh.vertexColors = new tColor4i[_copyFromMe.mesh.vertexCount];
        memcpy(this->mesh.vertexColors, _copyFromMe.mesh.vertexColors, _copyFromMe.mesh.vertexCount * sizeof(tColor4i) );
    }
}

My application crashes, because vertexColors wasn't initialized and is being copied. However it is NULL and shouldn't be copied.

Thanks.


This:

MeshObject::MeshObject(const MeshObject &_copyFromMe)

is a copy constructor. Because it is a constructor, it too should be setting the vertexColors member to some known & hopefully valid value, but it isn't, unless the value in the thing being copied is not NULL. But what if it is NULL? Basically, your if() needs an else.


The code is incomplete, but there's one guess I can make.

When you construct an object of MeshObject class using the above copy constructor and the source object has NULL in its mesh.vertexColors, the new object's mesh.vertexColors will contain garbage because you don't initialize it at all.

For example

MeshObject a;
// `a.mesh.vertexColors` is NULL

MeshObject b = a;
// `b.mesh.vertexColors` is garbage

You need to initialize mesh.vertexColors in the copy constructor in all cases, not only when the source is not null.


MeshObject o1;      // vertexColor is NULL
MeshObject o2(o1);  // vertexColor is undefined
MeshObject o3(o2);  // BOOM!


Basically, when your copy constructor is called, it does not call the normal constructor. The copy constructor must initialize the pointer to NULL in the same as the normal constructor. Else, it has a random value because you're using uninitialized memory. A decent compiler should be giving you a warning or error about this.


To piggyback on what others have said, as a general rule I will initialize all members in a copy constructor that I initialzed in a non-copy constructor unless there is some compelling reason not to do so. And I can't recall the last time there was such a reason.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜