问题遇到的现象和发生背景
最近看代码发现了空指针调用成员函数的情况,查看相关文章,基本都说明只要成员函数不调用this指针就不会有问题。
但是我自己试的时候发现下面的情况不会出现问题,感觉有点蒙了
struct TempClass
{
unsigned int id1;
unsigned long id2;
unsigned int id3;
TempClass()
{
id1 = 0;
id2 = 0;
id3 = 0;
DBG_LOG("construct fun!!");
}
void print()
{
DBG_LOG("this ptr:%d", this);
DBG_LOG("id1 ptr:%d offset : %d", &id1, (char*)&id1-(char*)this);
DBG_LOG("id2 ptr:%d offset : %d", &id2, (char*)&id2-(char*)this);
DBG_LOG("id3 ptr:%d offset : %d", &id3, (char*)&id3-(char*)this);
}
};
((TempClass*)0)->print();
打印结果如下:
this ptr:0
id1 ptr:0 offset : 0
id2 ptr:8 offset : 8
id3 ptr:16 offset : 16
上面是打印地址,如果打印成员变量的值,编译能通过,但是会核心已转储
struct TempClass
{
unsigned int id1;
unsigned long id2;
unsigned int id3;
TempClass()
{
id1 = 0;
id2 = 0;
id3 = 0;
DBG_LOG("construct fun!!");
}
void print()
{
DBG_LOG("this ptr:%d", this);
DBG_LOG("id1:%d ptr:%d offset : %d", id1, &id1, (char*)&id1-(char*)this);
DBG_LOG("id2:%d ptr:%d offset : %d", id2, &id2, (char*)&id2-(char*)this);
DBG_LOG("id3:%d ptr:%d offset : %d", id3, &id3, (char*)&id3-(char*)this);
}
};
((TempClass*)0)->print();
执行结果
44625 段错误 (核心已转储)
之前看文章提到,普通成员函数编译的时候会编译成普通函数,第一个参数是类类型的指针,也就是this。所以上面的print函数会编译程下面的函数
void print(TempClass* thisPtr)
{
DBG_LOG("this ptr:%d", thisPtr);
DBG_LOG("id1:%d ptr:%d offset : %d", thisPtr->id1, &thisPtr->id1, (char*)&thisPtr->id1-(char*)thisPtr);
DBG_LOG("id2:%d ptr:%d offset : %d", thisPtr->id2, &thisPtr->id2, (char*)&thisPtr->id2-(char*)thisPtr);
DBG_LOG("id3:%d ptr:%d offset : %d", thisPtr->id3, &thisPtr->id3, (char*)&thisPtr->id3-(char*)thisPtr);
}
但是我现在想不明白,thisPtr都已经是个空指针了,为啥还不会出错?请教下各位,这种情况是为什么?感谢!!