了解指针和“新”如何工作的问题

时间:2012-03-29 19:07:40

标签: c++ pointers

我目前正在学习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使用&运营商。对于我做错的任何解释都表示赞赏。

2 个答案:

答案 0 :(得分:2)

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 p2delete p3再次释放内存将再次导致未定义的行为,并且可能是崩溃,因为您已经删除了该内存。这就是分配新内存将解决崩溃的原因。

底线:不要多次释放相同的内存。

答案 1 :(得分:2)

这个问题可能源于你说

的事实
p = new int(10)

您只分配一个整数并将其初始化为10,而不是大小为10的数组。