2

Hi I have a problem with deleting an object array. Whenever I start my code, it works just fine, but when I close, I am getting the error: 0xC0000005: Access violation reading location 0xcccccccc. The code goes like this:

I initialize an instance of an object and immediately make an empty array out of it.

Class* classObject[15];

Afterwards, I define the empty array in a for loop.

for(int i = 0; i < 15; i++){
  classObject[i] = new Class();
}

When the application closes, the following code should delete the array out of memory.

for(int i = 0; i < 15; i++){
  delete classObject[i];
}

Instead of successfully closing, I am getting the Access violation error. How can I fix this problem and where? Also, are there maybe other ways I could create objects in a for loop?

4
  • 2
    Have you perhaps already free'd those pointers? Or set them to NULL or otherwise changed the pointers? Use of smart pointers (such as std::shared_ptr) might have mitigated this problem. Commented Dec 7, 2012 at 11:57
  • 7
    For such problems it is best if you can provide a complete example that demonstrates the behavior. See sscce.org Commented Dec 7, 2012 at 11:59
  • You've probably corrupted the free space arena with some earlier operation. Another possibility is that you're doing something bad in the destructor of Class. Commented Dec 7, 2012 at 12:05
  • If you solved the problem, post an answer and accept it. Answers do not go in questions. Commented Dec 8, 2012 at 13:21

1 Answer 1

3
class A
{
    public:
        A():a(0){};
    private:
        int a;
};

int main()
{
    A* arr[15];

    for(int i=0;i<15;i++)
    {
        arr[i] = new A();
    }
    for(int i =0;i<15;i++)
    {
        delete arr[i];
    }

    return 0;
}

There is no any error in my code .Have you delete the point before?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.