9

malloc失败后如何处理?

 3 years ago
source link: https://www.maixj.net/ict/malloc-fail-24253
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

malloc失败后如何处理?

2020年12月26日 / 6次阅读CC++

malloc在C语言中用来申请内存,这是非常重要的操作,但是如果失败,怎么处理呢?

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

1, 用exit函数(stdlib.h中定义)退出程序,退出前用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 freeing 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失败后的情况的内存,但最后还是退出,只是 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,这是我们要尽量避免的设计方案。

要malloc成功,需要OS判断系统有内存可以给进程使用,这可能会涉及一些page的swapping,是个很复杂的过程!


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK