gpt4 book ai didi

c - 总是检查 malloc 的内存?

转载 作者:太空狗 更新时间:2023-10-29 16:25:35 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com