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

后端 未结 6 1013
天命终不由人
天命终不由人 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 20:18

    Whenever you new (or new[]) memory you must delete (or delete[]) it or it will leak.

    Each time you call new you get returned a pointer to the heap allocated object if the new operation succeeds. If the pointer to this memory goes out of scope or is reassigned (i.e. what you are doing here) then you will be unable to delete the memory later.

    In your code example, only the last allocated memory will be destroyed. You can use something like process explorer or even task manager to check for memory leaks.

提交回复
热议问题