Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ delete [] object causes crash

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.

like image 754
hakeris1010 Avatar asked Dec 11 '22 01:12

hakeris1010


1 Answers

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[].

like image 127
Baum mit Augen Avatar answered Dec 29 '22 01:12

Baum mit Augen