Make malloc() return NULL instead of crashing the program?

Mic*_*ens 5 c crash malloc macos memory-management

I am allocating memory in a C program using malloc. It's possible for my program to allocate more memory than the system has room for, at which point the program crashes. For my purposes it would be better if malloc would just return NULL (like it's apparently supposed to), so I can catch the error. Instead what it does is it throws an error saying "No memory available to program now: unsafe to call malloc." And crashes the program.

How can I fix this?

Edit: I know that the program is crashing by itself and not because I'm trying to reference a null pointer. The program never directly calls malloc, but instead calls a function I wrote that calls malloc and then checks to see if it returns NULL. It's never saying that malloc returned NULL.

Edit 2: If it's helpful, here is the complete error output:

程序接收信号:“ EXC_BAD_ACCESS”。
sharedlibrary apply-load-rules所有
警告:无法恢复先前选择的框架。
暂时不可用的数据格式化程序,将在“继续”后重试。(正在调试的程序在从GDB调用的函数中发出
信号
。GDB 保留在接收信号的帧中。要更改此行为,请使用“ set unwindonsignal on”
。将放弃对包含函数(dlopen)的表达式的求值。 )
现在没有可用的内存来编程:不安全地调用malloc

msw*_*msw 2

一旦您通过缓冲区溢出、野指针或其他错误在堆上乱写乱画,malloc 的行为就会变得不确定,并且可能返回任何内容。

Malloc 只是一个用户空间库;其中不包含任何魔法。如果我在应用程序的客户名称链接列表上乱写乱画,当您稍后访问该列表时,您会得到奇怪的行为。Malloc 的行为方式相同,但由于 malloc 的使用是通过代码分布的,因此因果关系具有全局影响力。

所有的答案都围绕着这样一个事实:指针错误是 C 代码中最普遍的缺陷来源。你很幸运,你得到了一个 SIGBUS,它是缺陷的证据,它可能与故障发生的地点和时间相距甚远。使用valgrind帮助您找到真正的缺陷所在。