Search code examples
c++c++11memorynew-operatordelete-operator

Is it ok to "delete" memory allocated with "new[1]" and vice-versa?


Is this code legal?

int * a = new int[1];
delete a;

Or this one?

int * a = new int;
delete [] a;

Obviously, this doesn't seem right and should be discouraged at the very least but will it cause any actual problems (memory leaks and whatnot)?


Solution

  • Matching combination must be:-

    new; delete;

    new[]; delete[];

    If you mix these up you would get undefined behaviour. I have seen code blowing up due to this.