Snowman
Snowman

Reputation: 32091

Trouble with allocating new memory for array in C++

Ok I'm having a hard time understanding what I'm doing wrong. In my header file, I have a pointer to an array of pointers to images:

Image **images;
int maximum; //size

This is part of a class called scene. Now, scene has a member function called changemax, which changes the size of the images array. You can decrease or increase.

And so what I've done was set up a temporary array called newArray, copy all the values from this->images, delete this->images, then allocate new memory for images, copy from newArray to images, and then delete newArray.

I get over 100,000 errors with Valgrind, although the code does compile. In specific, I dont think Valgrind likes the line that says images=new Image*[newmax];

Upvotes: 0

Views: 181

Answers (2)

Omnifarious
Omnifarious

Reputation: 56098

This whole section of code is dead wrong and can be replaced by exactly one line that is correct:

images=new Image*[newmax];
for (int i=0;i<newmax;i++){
    if (newArray[i]!=NULL) {
        images[i]=new Image;
        *images[i]=*newArray[i];
    }
    else {
        images[i]=NULL;
    }

    delete newArray[i];
}
delete [] newArray;

and nothing even resembling that line appears in the code. Well, OK, the first line is vaguely similar, but only vaguely.

Upvotes: 1

James McNellis
James McNellis

Reputation: 355327

You certainly have a memory leak here:

newArray[i]=new Image;
if(images[i] !=NULL) {
    // ...
}
else {
    newArray[i]=NULL;
}

Why are you creating two new arrays? You only need to create one new array, copy the contents of the old array into the new array, destroy the old array, and then assign images to point to the new array.

Why are you creating new Image objects? Since you are only changing the size of the images array, you can simply move all of the pointers that you have into the new array without creating any new Image objects.

As I said in the comments, you should absolutely be using a std::vector or some other sequence container from the C++ Standard Library for this, for example a std::vector<Image>. The requirements are poor and I would strongly recommend a design change.

Upvotes: 2

Related Questions