When I use new [] to apply memory. In the end, I use delete to free memory (not delete[]). Will this cause memory leak?
Two types:
- Builtin types, like
int,char,double…
I am not sure. - class types.
I think may free leak. because the destruct function.
Many people and some books tell me, new[] -> delete[] ; new -> delete.
I want to know why.
so I check vs2010 source code, it must be use memory pool mechanism. It is long and complex . I can’t continue read.
How are delete and delete[] implemented?
If you use
new[], and thendelete(notdelete[]), then according to the langauge specification, it invokes undefined-behavior which means anything could happen. It may cause memory leak or may not. No such guarantee is given by the language, nor by the compiler.Short answer : because the specification says so.
Long answer: the functions which implement
newandnew[]are implemented differently:newassumes memory of one item is to be allocated, whilenew[]assumes memory ofnitem is to be allocated wherenis passed to the function as argument. So to undo the process (i.e to deallocate the memory), there should be two functions as well :deleteanddelete[]which are implemented differently, each makes some assumption about the memory allocated by their counterparts. For example,deletesimply assumes memory allocated for one item is to be deallocated; on the other handdelete[]needs to know the number of items for which memory is to be deallocated, so it assumes thatnew[]stores the number of items somewhere in the allocated memory, most commonly in the begginning of the allocated memory, and sodelete[]first reads that portion of memory which stores the number of items, and then deallocates the memory, accordingly.Note that
newandnew[]each calls the default constructor to construct the object(s) in the allocated memory, anddeleteanddelete[]calls the destructor to destruct the object before deallocating the memory.