Does calling new [] twice on the same pointer without calling delete [] in between cause a memory leak?

后端 未结 6 1019
天命终不由人
天命终不由人 2021-01-25 19:21

I\'ve heard that you should usually \"delete\" whenever you use \"new\", yet when I run a simple test program (below), it doesn\'t seem to make a difference which numbers I put

6条回答
  •  面向向阳花
    2021-01-25 19:58

    No, it's not sufficient.

    Each time you call new or new[], some memory is allocated, and you are given the address of that memory (in order to be able to use it). Each piece of memory must eventually be deleted (or delete[]d).

    You are storing that address in array, but then immediately overwriting it on the next iteration. Therefore you have no way of delete-ing all of pieces of memory that you've been allocated. Therefore you have a memory leak.

提交回复
热议问题