What if, memory allocated using malloc is deleted using delete rather than free

前端 未结 7 1708
渐次进展
渐次进展 2021-02-09 03:45

I came across an issue which I could not resolve.

My question is, if I used malloc to allocate memory and then memory block is delete using delete

7条回答
  •  Happy的楠姐
    2021-02-09 04:12

    When you call delete a pointer, the compiler will call the dtor of the class for you automatically, but free won't. (Also new will call ctor of the class, malloc won't.)

    In you example, a char array apparently don't have a dtor, so delete does nothing but return the memory. That's why it's okay. (Or vise versa, new a char array and then free it.)

    But there can still be a problem: what if new and malloc are borrowing memory from different heap manager?

    Imagine that, you borrow money from people A, and return to people B later. Even if you are okay with that, have you ever consider A's feeling?

    BTW, you should use delete [] pArray; to free an array allocated using new[].

提交回复
热议问题