我的代码编译如此,但我无法弄清楚为什么我一直收到这个错误,告诉我“Debug Assertion Failed”。这是为什么?
#include <iostream>
using namespace std;
struct Bag
{
int k;
};
int main ()
{
int *p1;
int *p2;
char p3;
//k = 100; // Assigns variable of type bag to 100
p1 = new int; // Variables created using the new operator are called dynamic variables
p2 = new int;
*p1 = 30;
*p2 = 50;
p3 = 'K';
*p1 = *p1 + *p2;
p1 = p2;
cout << "The sum of the two pointers is = " << *p1 << endl;
delete p1;
delete p2; // Delete the dynamic variable p1 and return the memory occupied by p1 to the freestore to be reused.
system ("Pause");
return 0;
}
答案 0 :(得分:1)
我猜你在那一行得到了Debug Assertion失败:
delete p2;
这里的问题是您设置“p1 = p2”,因此两个指针都指向包含整数“50”的内存位置。之后删除指针p1,这意味着UN分配包含整数“50”的内存位置。
此时p2未定义,尝试删除它将导致调试断言失败错误。