C++ 虚函数 修改虚表

#include<iostream>
#include<stdio.h>
using namespace std;
class CC
{
  public:
  virtual void Print()
  {
  cout<<"CC"<<endl;
  }   
} ;   
class Cst:public CC
{
  private:
  int a;
  int b;
  public:
  Cst(int a,int b):a(a),b(b) { }
  Cst() { }
  virtual void Print() {cout<<"first virual"<<endl;}
  char* name;
};
int main()
{
    
   

  Cst ss(0xFFFF,0xFFFF);
  ss.name =NULL;  
    
  int* ptr = reinterpret_cast<int*>(&ss);
  *ptr = 0xFFFFFFFF; //修改vptr指针,但是貌似虚函数还可以找到,对象还可以调用Print()
  //对象中指向该类的续表的指针vptr我都改动了,怎么还可以啊。??????  
  printf("%p\n",*ptr);
  ss.Print();//怎么还可以访问啊  
  system("pause");
  return 0;
}   
为什么改动了对象的虚表,对象还可以找到虚函数,访问????????
 
 
//因为我并没有用虚函数寻址,我直接用对象调用。那么是普通函数的调用。没有用到虚函数。下面的就有问题了
#include<iostream>
#include<stdio.h>
using namespace std;
class CC
{
    public:
        virtual void Print()
        {
            cout<<"CC"<<endl;
        }     
} ;    
class Cst:public CC
{
    private:
    int a;
    int b;
    public:
        Cst(int a,int b):a(a),b(b) { }
        Cst() { }
      virtual void Print() {cout<<"first virual"<<endl;}
      char* name;
};
void  chengedPrintf()
{
	cout << 1<<endl;
}
int main()
{
    
    Cst* ss = new Cst(0xFFFF,0xFFFF);
    ss->name =NULL; 
   
    int* ptr = reinterpret_cast<int*>(ss);
    int* pchengd = reinterpret_cast<int*>(chengedPrintf);
    *ptr = (int)(&pchengd); 
    ss->Print(); //这个时候修改了函数地址了,访问时 chengedPrintf

    system("pause");
    return 0;
}         



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值