为什么执行虚构函数会导致程序崩溃
代码如下:
#include <iostream>
#include <vector>
using namespace std;
class Base
{
public:
int a;
Base(istream& in) { read(in);}
Base():a(0) {}
virtual ~Base(){}
protected:
istream& read(istream& in)
{
in >> a;
return in;
}
};
class Son:public Base
{
public:
int b;
Son(istream& in):Base(in)
{
read(in);
}
Son():b(1) {}
~Son(){}
istream& read(istream& in)
{
in >> b;
return in;
}
};
int main()
{
Son test(cin);
Base* b = &test;
delete b;
return 0;
}
#include <stdio.h>
#include <malloc.h>
int main()
{
char str[] = "hello!";
free(str);
//在这里崩溃,str的内存块是在栈中,free把它当成堆中的内存块去释放
//释放时会很一些写信息的操作,破坏了栈中的数据
//堆内存块中还会有一些链接指针数据,栈中的数据没有,free当它有,
//把不明数据当指针去使用,那就不知道会读写到什么地方了
}