如何处理malloc失败

Last Updated: 2024-01-08 02:14:06 Monday

-- TOC --

著名的申请内存的malloc,这么重要的操作,如果失败,怎么处理呢?

一般在malloc之后,都要立刻判断指针是否为NULL,如果为NULL,就是申请内存失败了。

失败后,你可以:

  1. 调用exit函数退出程序,退出前用fprintf往stderr抱怨一下。
  2. 想办法free一些其它没用的内存,然后重新malloc。
  3. 尽量避免busy loop waiting and trying, 除非你知道自己的做什么。

下面内存来自stackoverflow的一个回答:

In general, a modern malloc() implementation will return NULL only as an absolute last resort, and trying again will definitely not help. The only thing that will help is to free some memory and then trying again. If your application holds any expendable resources, this would be the time to free them, and then give it another shot.

In some environments, a useful practice is to allocate a small amount of memory as a rainy-day fund. If malloc() ever does return NULL, you can free that rainy-day fund, and then allocate whatever resources you need to be able to handle the error and exit gracefully. This was a common practice when programming with the old Macintosh Toolbox; if malloc() returned NULL, you could use that space to create a dialog to report the problem before exiting. (也许应该直接使用rainy-day fund)

malloc的实现,已经考虑各种情况,返回NULL,说明在尽力之后,还是没有可用内存。上文还提到了一个小技巧:rainy-day fund,就是提前申请一小块专门用来处理malloc失败后的情况的内存,但最后还是退出,只是退出可以very graceful,某些情况下可以考虑。

再看另一个回答:

In a single-threaded program "trying again" without freeing any memory between tries make no practical sense. It will just loop forever.

In a multi-threaded program this might "work", if another thread running in parallel suddenly decides to free some of its own memory. The loop in such case would constitute a classic "busy waiting" loop. But even in this case such code has very little practical value for more reasons than one.

单线程程序,malloc失败后,如果没有free,直接继续申请,没有啥意义,结果就是个死循环。不过,多线程的程序,malloc失败后直接继续申请,有可能会在某个时刻成功,这就是经典的busy waiting loop,但这是我们要尽量避免的设计方案。

本文链接:https://cs.pynote.net/sf/c/202112221/

-- EOF --

-- MORE --