What REALLY happens when you don't free after malloc?

前端 未结 18 1008
南旧
南旧 2020-11-22 01:32

This has been something that has bothered me for ages now.

We are all taught in school (at least, I was) that you MUST free every pointer that is allocated. I\'m a

18条回答
  •  春和景丽
    2020-11-22 02:21

    If you're developing an application from scratch, you can make some educated choices about when to call free. Your example program is fine: it allocates memory, maybe you have it work for a few seconds, and then closes, freeing all the resources it claimed.

    If you're writing anything else, though -- a server/long-running application, or a library to be used by someone else, you should expect to call free on everything you malloc.

    Ignoring the pragmatic side for a second, it's much safer to follow the stricter approach, and force yourself to free everything you malloc. If you're not in the habit of watching for memory leaks whenever you code, you could easily spring a few leaks. So in other words, yes -- you can get away without it; please be careful, though.

提交回复
热议问题