Question

I had a similar issue with C, but my problem now is actually more similar to this.

Unfortunately, I'm just learning C++, and I can't see how to apply the solution to my previous issue (if it indeed does apply), and the latter post was a specific problem with his code, that is more complex than my own.

Here is the relevant code:

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;
}

As you can see, p and tmp point to arrays that have initial sizes, and are freed within a few lines. Crucially, I cannot see how "a pointer being freed was not allocated" - p is allocated on declaration, tmp within the loop, then p is freed and reallocated, then tmp is freed, and so the loop continues...

I also tried implementing via two loops, but then the printed 'points' are (0, 0), whatever they actually are - I can't spot why?

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++;
}
Was it helpful?

Solution

There is an error in almost every line here:

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"

OTHER TIPS

You seem to misunderstand how pointers work. tmp is assigned a new point[] in the second line of your loop, but in the third line, tmp is overwritten by another value, destroying any reference to the memory just allocated... This causes a memory leak. I know, this was not your question, but I think you should think the whole thing over...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top