内存分配失败时 g_strdup 是否返回 NULL?
glib 文档缺少许多我认为 API 文档绝对应该包含的重要内容。例如 g_malloc 的条目表示 没有什么它会在内存分配失败时崩溃(与标准malloc
的行为形成直接对比,其名称暗示它模仿)。仅当您碰巧注意到还有一个名为 g_try_malloc 并阅读其描述,您将被告知 g_try_malloc
尝试分配 n_bytes,失败时返回 NULL。对比 使用 g_malloc(),它会在失败时中止程序。
现在的问题是,glib 有一个函数 g_strdup,它也没有提到任何可能返回 NULL 的内容。我认为不会,因为暗示它将在内部使用 g_malloc。会吗?
The glib documentation lacks many important things that I think API documentation absolutely should include. For instance the entry for g_malloc says nothing about that it will crash upon memory allocation failure (in direct contrast to the behaviour of the standard malloc
, which the name implies that it mimics). Only if you happen to notice that there also is a variant named g_try_malloc and read its description you will be informed that g_try_malloc
Attempts to allocate n_bytes, and returns NULL on failure. Contrast
with g_malloc(), which aborts the program on failure.
Now for the question, glib have a function g_strdup
which also does not mention anything about possibly returning NULL. I assume that it will not since it is implied that it will be using g_malloc internally. Will it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不过,文档确实这么说。查看“内存分配”的介绍部分GLib 手册中的“ 页:
这适用于任何分配内存的库调用,因此也适用于 g_strdup() 。
The documentation does say it, though. Check the introductory section to the "Memory Allocation" page in the GLib manual:
This goes for any library call that allocates memory, and therefore for
g_strdup()
too.