0

I am getting heap crash in delete call of overloaded delete. Please help me in resolving this issue.

class number {
    int *series;
public:
    void* operator new(size_t size){
        number *n = ::new number;
        n->series = new int[size];
        printf("new %p %p\n", n, n->series);
        return n;
    }
    void operator delete(void *ptr) {
        number *n = (number*)ptr;
        printf("delete %p %p\n", n, n->series);
        delete (int*)n->series;// why crash here?
        ::delete n;
    }
};

int main() {
    number *n= new number;
    delete n;
    return 0;
}
  • 1
    `delete (int*)n->series;` must be `delete [] n->series;` – HolyBlackCat May 07 '16 at 17:09
  • Just out of curiosity, why don't you delegate series initialization to constructor ? – bisthebis May 07 '16 at 17:10
  • 1
    Also, it's a bit weird to use custom operators new and delete in your case. It's just not a good code. You should use a constructor and destructor instead. This will allow you to create new objects without `new`, which is faster and probably better in this case. – HolyBlackCat May 07 '16 at 17:11
  • 1
    @NicolBolas Based on that meta thread, I'm impressed you found this duplicate! I was searching for a while and gave up. – Barry May 07 '16 at 17:12

1 Answers1

3

You allocated series as an array, using new int[size]. So you must free it as one: delete [] n->series.

(I'm not sure why to have the cast there, but it's a bad idea. If you tell the compiler to ignore your errors it just makes things harder.)

Alan Stokes
  • 18,815
  • 3
  • 45
  • 64