Does every malloc call have to be freed

后端 未结 9 828
伪装坚强ぢ
伪装坚强ぢ 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:23

    Yes. If you malloc, you need to free. You are guaranteeing memory leaks while your program is running if you don't free.

    Free it.

    Always.

    Period.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-20 16:26

    1) The same way you'd free the memory normally, i.e.

    p = func();
    //...
    free(p);
    

    The trick is in making sure that you always do it...

    2) Generally speaking, yes. But you should still free any memory you use as good practice. Not spending the time to figure out where to free the memory is just being lazy.

    0 讨论(0)
提交回复
热议问题