运行这段代码会导致堆损坏
#include <iostream>
using namespace std;
class X
{
public:
char* charArr;
int *intArr1;
int *intArr2;
int *intArr3;
X()
{
charArr = new char[] { 5, 5, 5, 5 };
intArr1 = new int[] { -10, -10, -10 };
intArr2 = new int[] { -20, -20, -20};
intArr3 = new int[] { -30, -30, -30};
}
~X()
{
delete[] charArr;
delete[] intArr1;
delete[] intArr2;
delete[] intArr3;
}
};
int main()
{
X x;
return 0;
}
我做错了什么? 我使用visual studio,这是错误消息: exception
答案 0 :(得分:0)
我也使用Visual Studio。当我尝试开始调试时。写作时出现了一些错误:
charArr = new char[] { 5, 5, 5, 5 };
intArr1 = new int[] { -10, -10, -10 };
intArr2 = new int[] { -20, -20, -20};
intArr3 = new int[] { -30, -30, -30};
我认为你应该写如下:
#include <iostream>
using namespace std;
class X
{
public:
char* charArr;
//int *intArr1;
//int *intArr2;
//int *intArr3;
X()
{
charArr = new char[4];
for(int i = 0; i < 4; i++)
charArr[i] = 5;
//intArr1 = new int[] { -10, -10, -10 };
//intArr2 = new int[] { -20, -20, -20};
//intArr3 = new int[] { -30, -30, -30};
}
~X()
{
delete[] charArr;
// delete[] intArr1;
// delete[] intArr2;
// delete[] intArr3;
}
};
int main()
{
X x;
return 0;
}
然后它运作良好。