正在释放的指针未被分é…,动æ€æ•°ç»„C ++

时间:2014-01-30 23:25:12

标签: 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;
}

如您所è§ï¼Œpå’Œtmp指å‘具有åˆå§‹å¤§å°çš„数组,并且在几行内被释放。至关é‡è¦çš„是,我看ä¸å‡ºâ€œé‡Šæ”¾çš„指针是如何分é…的†- p在声明中分é…,tmp在循环内,然åŽp被释放并é‡æ–°åˆ†é…,然åŽ{{1释放,所以循环继续......

我也试过通过两个循环实现,但是打å°çš„“点â€æ˜¯tmp,无论它们实际是什么 - 我都找ä¸åˆ°åŽŸå› ï¼Ÿ

(0, 0)

2 个答案:

答案 0 :(得分:8)

这里几乎æ¯ä¸€è¡Œéƒ½æœ‰ä¸€ä¸ªé”™è¯¯ï¼š

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"

答案 1 :(得分:1)

你似乎误解了指针是如何工作的。 tmp在循环的第二行中被赋予一个新的point [],但是在第三行中,tmp被å¦ä¸€ä¸ªå€¼è¦†ç›–,销æ¯å¯¹åˆšåˆ†é…的内存的任何引用...这会导致内存泄æ¼ã€‚我知é“,这ä¸æ˜¯ä½ çš„问题,但我认为你应该考虑整件事......