Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot delete unsigned char* array

In one of my objects, I create an unsigned character array member to store some image data:

    unsigned char* imageData;

and in the constructor I initialize it with new:

    MyObject::MyObject()
    {
        int imageSize = 6054400;
        imageData = new unsigned char[imageSize];
    }

imageData gets filled throughout the course of the loop.

This object (MyObject) won't get deleted until the very end of the loop, but I need imageData to be deleted midway through the loop. So I just created this function:

    void MyObject::DeleteAllMembers
    {
        delete [] imageData;
    }

and I call it at the end of the loop:

    theObj.DeleteAllMembers();

The problem is that every time my program gets to the line of code:

    delete [] imageData;

it crashes, leaving this error message:

error

At this point I have no idea why this is happening.

Some of the things I've tried have been:

  • initializing imageData with imageSize+1 instead of just imageSize
  • moving the delete command to the destructor and manually deleting the object each run through the loop
  • using delete imageData instead of delete [] imageData, even though I'm fairly sure that I need to use delete []
  • I've tried doing imageData = 0 after deleting it, unfortunately my program still crashes at the delete [] imageData line.
  • I've tried using memset(&imageData, 0, imageSize);, but that gave me an access violation error.

Each time, the program still crashes at that same line. I know someone is looking at my code thinking "You moron, all you have to do is ____________________." Can someone please tell me what I'm doing wrong?

EDIT: Sorry I said something incorrect. I create this object each time at the beginning of the loop and it gets deleted at the end of the loop, I don't know why I said at the beginning and end of the program.

like image 494
xcdemon05 Avatar asked May 17 '26 21:05

xcdemon05


1 Answers

You may want to make a slight addition to prevent multiple deletion of the same pointer:

void MyObject::DeleteAllMembers
{
    delete [] imageData;
    imageData = 0; // <-- here
}
like image 177
Alexey Frunze Avatar answered May 19 '26 10:05

Alexey Frunze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!