Bus Error Upon Calling Delete (C++)
I've been creating a class that takes a bunch of images and overlays them onto one BMP. For some reason upon 开发者_JS百科running the code I'm getting a segfault and I've tracked it down to this method. Essentially the if statement checks to see if there is a valid index in the array of images to place this new image in. If it is valid then it deletes whatever was there previously and sets that index to this new Image. The Class is called Scene and is comprised of an array of Image pointers. So what I'm doing is replacing the image that one of those pointers points to. Somehow its not working though. If the pointer is NULL the delete command shouldn't cause any problems, so I don't see what could be going wrong. This code is acting on a Scene that has an array of Image pointers of length 5.
void Scene::addpicture(const char* FileName, int index, int x, int y)
{
if (index<0 || index>maxnum-1)
{
cout << "index out of bounds" << endl;
}
else
{
Image* extra;
extra = new Image;
extra->ReadFromFile(FileName);
delete imagelist[index];
imagelist[index] = extra;
imagelist[index]->xcoord=x;
imagelist[index]->ycoord=y;
}
}
Can anyone help. It would be much appreciated.
Thanks
I've edited to include the constructor:
Scene::Scene(int max)
{
Image** imagelist = new Image*[max];
for(int i=0; i<max; i++)
{imagelist[i] = NULL;}
maxnum = max;
}
I've also commented out the main method so that the only functions being called are
Scene* set = new Scene(5);
set->addpicture("in_01.bmp", 0, 0, 0);
In your constructor you have a local imagelist, but you are using a field imagelist in addpicture. You are shadowing the imagelist field in the constructor and the field never gets initialized.
Fix it by replacing this line:
Image** imagelist = new Image*[max];
With this:
imagelist = new Image*[max];
A SEGFAULT means that you're trying to access a location outside of what you should be. In your comment to Messa, you say that it's happening at the delete
command.
So, I ask you: When you construct the Scene
class, do you explicitly initialize the pointers in imagelist
to NULL? In other words, are there lines like:
for (i=0; i<maxnum; i++) {
imagelist[i] = NULL;
}
in your constructor, or are you assuming that uninitialized arrays start as 0-filled? (Unlike most languages, that assumption is bad in C++.)
This code looks OK, I think error is in some other part of the program. Maybe imagelist
array is not initialized to NULL
? Or maxnum
is not the actual size of imagelist
. Or something other.
What exactly is failing - do you have traceback?
精彩评论