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