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

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

    It helps to understand correctly what you are actually doing.

    You are not calling new[] twice on the same pointer. You are calling new[] twice, and storing both results into the same pointer. new[] simply returns a pointer to the allocated memory. To avoid leaking memory, you have to free that memory again at some point. But the pointer is not the memory, it is just a pointer telling you where the allocated memory is.

    So you can always overwrite the pointer, setting it to point to a new, different address. And then you just lost all knowledge of where it used to point to. If it used to point to memory that you ought to free, then you can no longer find that chunk of memory, so you can no longer call delete[] on it, and so... it is leaked.

提交回复
热议问题