我目前正在学习我的 C++ 书籍(编程:Stroustrup 使用 C++ 的原则和实践)中的指针。这本书让我做了以下“练习”以习惯指针和数组。我评论了与我的问题无关的练习部分。
int num = 7;
int* p1 = #
// output p1 address and content...
int* p2 = new int(10);
// initialise each element, and output content...
int* p3 = p2;
p1 = p2;
// output p1 and p2 address and content...
delete[] p1;
/* As all pointers now point to the same array created in the free store,
I was under the impression that I only needed to use delete for 1 of
the pointers to deallocate memory,as above, but the program crashes
if I don't do it for all 3 and execute next section of code? */
p1 = new int(10);
p2 = new int(10);
// Initialise each array to a different range of numbers using a loop,
// output each array, change elements in p2 to be the same as p1, output...
delete[] p1;
delete[] p2;
最后一部分是我遇到麻烦的地方。输出每个数组时,元素值是相同的。我的猜测是 p1 仍然 == p2,因为几行之前的代码。我认为当您使用“new”关键字时,它会返回一个地址,引用一个不同的、新分配的内存块,因此 p1 将不再 == p2。我让它工作的唯一方法是直接创建 2 个数组并让 p1 和 p2 使用 & 运算符引用它们。感谢任何关于我做错了什么的解释。
最佳答案
int* p2 = new int(10);
// initialise each element, and output content...
int* p3 = p2;
p1 = p2;
// output p1 and p2 address and content...
delete[] p1;
此代码会导致未定义的行为,因为您使用new
进行分配并使用delete[]
释放内存。
int* p2 = new int(10);
//allocates a single int with value 10
不同于
int* p2 = new int[10];
//allocates an uninitialized array of 10 ints
除此之外(尽管是一个严重的问题,因为所有未定义的行为),问题是这样的:
int* p2 = new int(10);
int* p3 = p2;
p1 = p2;
//all pointer point to the same memory location
delete[] p1;
//delete that memory
//all three pointers are now invalid
尝试通过delete p2
或delete p3
再次释放内存将再次导致未定义的行为,并且可能会导致崩溃,因为您已经删除了该内存。这就是分配新内存将修复崩溃的原因。
底线:不要多次释放相同的内存。
关于c++ - 理解指针和 'new' 如何工作的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9931828/