are pointers released from memory when c++ program end?

☆樱花仙子☆ 提交于 2019-12-19 08:06:14

问题


This is a beginner question but I learned programming with c# and I am now moving to c++ and now that I am working with pointers, I know that I have to free them from memory when I'm done with them but when the program is closed are they removed from the memory or do they stay there?


回答1:


When your program ends, all the memory it used (whether dynamically allocated or not) is returned to the operating system. It doesn't matter if it's a C program, a C++ program, a C# program, or any other kind of program you might be writing.

Now, just because the OS will reclaim the memory doesn't mean you can be cavalier about memory management. While your program runs, you should try to take care of freeing any memory you're done with. Not doing so will cause "memory leaks", and those can certainly affect your program and the system it's running on, at least while your program is running.




回答2:


Note that its not the pointer that needs deallocation but the pointed object.

The answer depends on type of memory the pointers point to:

  • If the pointer points to automatic object then the objects are cleaned implicitly.
  • If the pointer points to objects allocated dynamically using new or new [] or malloc or calloc, then they need to be explicitly deallocated by resp calling delete or delete [] or free.

Note that it is advisable to Use dynamic allocations sparingly and if you must, Use Smart pointers instead of raw pointers.

EDIT:
If your question is:
What happens if your program doesn't deallocate memory and exits?

Answer is:
OS reclaims it. The OS simply takes back all the memory it allocated to a process it does not understand whether your program leaked memory or not.
But it is always a good practice to clean up your own mess yourself.
If you have an class who's destructor does have code with side-effects then not calling delete on the dynamically allocated pointer results in Undefined Behavior and it renders your code completely dangling at compilers mercy.




回答3:


The memory allocated by you ( e.g. using the New keyword) will remain there unless you delete it! If you are talking about the pointer itself, then yes! At the end of your program the pointer will just get wiped out!



来源:https://stackoverflow.com/questions/12875177/are-pointers-released-from-memory-when-c-program-end

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!