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

标签 c++ arrays pointers memory-management dynamic-arrays

我有 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/

相关文章:

c++ - 使用 g++ -m32 选项编译 C++

javascript - 创建 Id 数组

c - "Redefinition - Different Basic Types"在 C 中使用指针时出错

c - 使用 C 提取 Wiki 链接

c++ - 如何在 QTreeWidget header 中添加按钮或其他小部件?

c++ - 将字符串以外的任何内容附加到 std::stringstream 返回 0

c++ - 如何防止另一个线程修改状态标志?

python - 将数组拆分为预测矩阵和响应向量

c - 为什么下面程序中的 fgets 函数(请参阅详细信息)将字符串的长度解释为多一个字符?

c - 将带链表的归并排序从 C 翻译成 MIPS