4

I made a dynamic array of objects. When I call delete[] , program crashes and stops responding. But it does strange behavior: calls all destructors and crashes. look at this code and output. All the memory for all arrays is allocated.

//main file
#include "myobject.h"

int size;
myObject *foo;

//some operations to estimate size

foo = new myObject[size];

//some operations with myObject

std::cout<<"size: "<<size<<"\n";
std::cout<<"Deleting object\n";

size=0;
delete [] foo;

Next file:

//myobject.h

class myObject
{
    public:
    int number;

    Object1 ob1[64]
    Object2 *ob2;

    myObject(){ };
    ~myObject()
    {
        std::cout<<"delete "<<number<<"\n";

        delete [] ob1;
        delete [] ob2;
    };
}

And the output:

size: 11

Deleting object

delete 10

delete 9

delete 8

delete 7

delete 6

delete 5

delete 4

delete 3

delete 2

delete 1

delete 0

And then it crashes and stops responding.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
hakeris1010
  • 285
  • 1
  • 5
  • 12

2 Answers2

7

You can only call delete[] on pointers returned by new[], and you must do this exactly once. The same applies for delete and new.

Particularly, you cannot delete[] obj1 because it is a built in array, not a pointer, and obj2 only if it points to not-freed memory allocated with new[].

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
6
delete [] ob1;

You didn't new obj1; it's an array contained in the object. Deleting anything that wasn't allocated with new gives undefined behaviour, which might well be a crash.

If you're going to juggle pointers like this, then you'll need to learn about the Rule of Three to avoid the next deathtrap you'll encounter. Then learn about RAII and smart pointers, and forget about this dangerous nonsense.

Community
  • 1
  • 1
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644