c - 总是检查 malloc 的内存?

标签 c architecture system

我经常发现自己在做以下事情(在非关键组件中):

some_small_struct *ptr=(some_small_struct *) malloc(sizeof(some_small_struct));
ptr->some_member= ...;

换句话说,我为一个小结构动态分配内存,我直接使用它而不检查 malloc 的指针。我知道程序总是有可能得不到它要求的内存(呃!),但请考虑以下几点:

If the program can't even get some memory for a small structure off the heap, maybe there are much bigger problems looming and it doesn't matter after all.

此外,如果处理空指针会进一步加剧不稳定情况怎么办? (例如,尝试记录条件调用更多不存在的资源等)

我的推理是否合理(足够)?

更新:

  1. “safe_malloc”函数在调试时很有用,否则可能会有用
  2. +X 访问可以隐藏 NULL 指针的根本原因
  3. 在 Linux 上,“乐观的内存分配”可以避免出现 OOM(内存不足)情况

最佳答案

取决于平台。例如,在 Linux 上(默认情况下)检查 NULL 没有多大意义:

http://linux.die.net/man/3/malloc

By default, Linux follows an optimistic memory allocation strategy. This means that when malloc() returns non-NULL there is no guarantee that the memory really is available. This is a really bad bug. In case it turns out that the system is out of memory, one or more processes will be killed by the infamous OOM killer.

关于c - 总是检查 malloc 的内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1941323/

相关文章:

c - 如何翻转和反转 C 中的 int?

objective-c - 在 C/Objective-C 中使用带有系统函数的 cd ~ 不能正确地 cd

c - 传递参数 1 of 'strcmp' 错误/预期 'const' char *' but argument is of type ' int'

c# - 如何将 PropertyBag 类存储到数据库中

terminology - 任何一段代码正在做的12件事

java - 如何实现应用程序故障转移?

java - 如何重复/循环/返回类

c - 是否可以在 Windows api 中覆盖 MFT 文件表?

c - 如何找到地址空间中的漏洞?

MySQL C API - 批量插入性能问题