Does every malloc call have to be freed

后端 未结 9 863
伪装坚强ぢ
伪装坚强ぢ 2020-12-20 16:04

From what I understand because malloc dynamically assigns mem , you need to free that mem so that it can be used again.

  1. What happens if you return a char* that
9条回答
  •  既然无缘
    2020-12-20 16:26

    1. If you have a pointer to memory created by malloc, freeing that memory, using that pointer, will do the right thing. Yes, there is some magic involved; this will be taken care of by your compiler.

    2. Yes, if you ignore the memory freeing, and exit the application, the OS will release the memory. However, it's considered bad practice to leave it unfreed. The OS may not do the right thing (especially in embedded settings), or may not do it in a timely fashion. Also, if you're running your program continuously, you may end up consuming a growing amount of memory, eventually consuming it all, and running out of memory and crashing.

提交回复
热议问题