首页 » 信息技术 »

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,是个很复杂的过程!

本文链接:https://www.maixj.net/ict/malloc-fail-24253

相关文章

留言区


前一篇:
后一篇:
-->只要几分钟回答问卷,就能轻松赚现金!

栏目精选

云上小悟,麦新杰的独立博客

Ctrl+D 收藏本页

栏目


©Copyright 麦新杰 Since 2014 云上小悟独立博客版权所有 备案号:苏ICP备14045477号-1。云上小悟网站部分内容来源于网络,转载目的是为了整合信息,收藏学习,服务大家,有些转载内容也难以判断是否有侵权问题,如果侵犯了您的权益,请及时联系站长,我会立即删除。

go to top