gpt4 book ai didi

c++ - 未分配正在释放的指针,动态数组 C++

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:26:32 26 4
gpt4 key购买 nike

我有 a similar issue with C , 但我现在的问题实际上是 more similar to this.

不幸的是,我只是在学习C++,我看不到如何将解决方案应用于我之前的问题(如果它确实适用),而后一个帖子是他的代码的特定问题,即更多比我自己的复杂。

相关代码如下:

double n1, n2; //temporary data for user entry
int pcount = 0; //size of my array
struct point{double x; double y;};
point *p = new point[1]; //my array
point *tmp; //temporary array while resizing

while (points >> n1 >> n2){ //for each element the user enters,
pcount++; //increase the array size
tmp = new point[pcount]; //allocate new memory for the array
tmp = p; //copy the elements from the old to the temporary
delete [] p; //delete the old array
p = new point[pcount]; //allocate memory for the new array
p = tmp; //copy the elements from the temporary to the new array
delete [] tmp; //delete the temporary
p[pcount-1].x = n1; //now push back the new element
p[pcount-1].y = n2;
}

如您所见,ptmp 指向具有初始大小的数组,并在几行内被释放。至关重要的是,我看不到如何“未分配正在释放的指针”- p 在声明中分配,在循环内分配 tmp,然后是 p被释放并重新分配,然后 tmp 被释放,所以循环继续...

我也尝试通过两个循环实现,但是打印的“点”是 (0, 0),无论它们实际是什么 - 我无法找出原因?

while (points >> n1 >> n2){
pcount++;
}
p = new point[pcount];
int i = 0;
while (points >> n1 >> n2){
p[i].x = n1;
p[i].y = n2;
i++;
}

最佳答案

这里几乎每一行都有一个错误:

point *p = new point[1]; // Allocation #1
tmp = new point[pcount]; // Allocation #2
tmp = p; // Allocation #2 lost (memory leak)
delete [] p; // Now 'tmp' is "pointing to junk"
p = new point[pcount]; // Allocation #3
p = tmp; // Allocation #3 lost (memory leak), and 'p' is "pointing to junk"
delete [] tmp; // Segmentation fault, since 'tmp' is "pointing to junk"
p[pcount-1].x = n1; // Segmentation fault, since 'p' is "pointing to junk"
p[pcount-1].y = n2; // Segmentation fault, since 'p' is "pointing to junk"

关于c++ - 未分配正在释放的指针,动态数组 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21469611/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com