NULL pointer is the same as deallocating it?

前端 未结 11 2505
一个人的身影
一个人的身影 2021-02-18 18:29

I was working on a piece of code and I was attacked by a doubt: What happens to the memory allocated to a pointer if I assign NULL to that pointer?

For instance:

11条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-18 19:00

    Under most circumstances, that will cause a memory leak in your process. You have several options for managing memory in C++.

    1. Use a delete to manually free memory when you're done with it. This can be hard to get right, especially in the context of exception handling.

    2. Use a smart pointer to manage memory for you (auto_ptr, shared_ptr, unique_ptr, etc.)

    3. C++ does not come with a garbage collector, but nothing prevents you from using one (such as the Boehm GC) if you want to go down that route.

提交回复
热议问题