为什么执行虚构函数会导致程序崩溃
代码如下:
#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;
}
调试发现执行到~Base()程序就出错了,求解,本人第一次上论坛,还请各位多多相助 调试 类
[解决办法]
二楼说的很正确啊
[解决办法]
这个问题与析构无关,与虚函数无关,与C++语言无关。
#include <stdio.h>
#include <malloc.h>
int main()
{
char str[] = "hello!";
free(str);
//在这里崩溃,str的内存块是在栈中,free把它当成堆中的内存块去释放
//释放时会很一些写信息的操作,破坏了栈中的数据
//堆内存块中还会有一些链接指针数据,栈中的数据没有,free当它有,
//把不明数据当指针去使用,那就不知道会读写到什么地方了
}