dynamic arrays- error pointer being freed was not allocated

Hello. I have a class called Book and I am trying to create a dynamic pointer based array of the class. When I try to run the program I keep getting the error: pointer being freed was not allocated at the line of code that says "delete [] A;". I am using Xcode to run the program. Does anyone know what I am doing wrong?

Book *changeArraySize(Book *A, int &size, double factor)
{
int i;
int newsize = size*factor;
Book *A2 = new Book[newsize];
for(i = 0; i < size; i++){
*(A2+1) = *(A+1);}
size = newsize;
delete [] A;
A = NULL;
return A2;
}
Is A null or pointing to the first element of an array that was created using new?
Last edited on
It's pointing to the first element of an array created using new.
> A = NULL;
conceptual error, that change is local to the function, it would not be reflected to the parameter in the call.

> *(A2+1) = *(A+1);
¿how many times do you want to set the second element?
¿are you sure that such element exists?

http://www.cplusplus.com/forum/general/112111/
Sorry! that *(A2+1) = *(A+1) should be *(A2+i) = *(A+i) so that so the elements from the original array are copied to the new array (I changed that part of the code after I posted my question) before A is deleted.
I included A = NULL so the pointer wouldn't be dangling
In this case can you have just delete A; without the []?
@i8pp: No.
if you allocate with new[] you must deallocate with delete[]
if you allocate with new you must deallocate with delete


> I included A = NULL so the pointer wouldn't be dangling
again, conceptual error
1
2
3
Book *math = new Book[n];
copy = changeArray(math, n, 3.14);
//math is dangling here 
Ah, I see. Thank you.
Topic archived. No new replies allowed.