orl*_*rlp 64
xmalloc()是一个非标准的功能,其座右铭是成功或死亡.如果它无法分配内存,它将终止您的程序并打印错误消息stderr.
分配本身也不例外; 只有在没有内存可以分配的情况下的行为是不同的.
使用malloc(),因为它更友好和标准.
R..*_*R.. 26
xmalloc不属于标准库.它通常是懒惰程序员非常有害的函数的名称,这在许多GNU软件中很常见,abort如果malloc失败则会调用它们.根据程序/库的不同,它也可以转换malloc(0)为malloc(1)确保xmalloc(0)返回唯一指针.
在任何情况下,abort荷兰国际集团的malloc失败是非常非常恶劣的行为,特别是对库中的代码.其中一个最臭名昭着的例子是GMP(GNU多精度算术库),它会在计算机内存不足时中止调用程序.
正确的库级代码应该始终通过退出它在中间的任何部分完成的操作并将错误代码返回给调用者来处理分配失败.然后,调用程序可以决定要做什么,这可能涉及保存关键数据.
eva*_*low 19
正如其他人所提到的那样,它xmalloc经常被实现为一个包装函数,它调用操作系统提供的malloc和盲目的调用abort或者exit如果它失败了.但是,许多项目包含一个xmalloc在退出之前尝试保存应用程序状态的函数(例如,参见neovim).
就个人而言,我认为xmalloc这是一种特定于项目的扩展 malloc而不是退出 malloc.虽然我不记得曾经看到一个版本不拉闸打电话abort或者exit,他们有的做了很多不止于此.
所以,这个问题的答案"有什么之间的区别xmalloc和malloc是:这取决于xmalloc.是非标准,具体项目的功能,所以它可以做任何事情都知道肯定的唯一途径就是阅读代码.
小智 7
K&R C中xmalloc.c的原始示例
#include <stdio.h>
extern char *malloc ();
void *
xmalloc (size)
unsigned size;
{
void *new_mem = (void *) malloc (size);
if (new_mem == NULL)
{
fprintf (stderr, "fatal: memory exhausted (xmalloc of %u bytes).\n", size);
exit (-1);
}
return new_mem;
}
Run Code Online (Sandbox Code Playgroud)
然后在你的代码头(早期)你放
#define malloc(m) xmalloc(m)
在编译之前默默地重写源代码.(您可以通过直接调用C预处理器并保存输出来查看重写的代码.)
如果您的程序崩溃不是您想要的,您可以做一些不同的事情
用户不喜欢将他们的数据丢失到程序中的内置崩溃命令.
xmalloc 是libiberty的一部分
https://gcc.gnu.org/onlinedocs/libiberty/index.html这是一个GNU utils库.
malloc 是ANSI C.
xmalloc在许多重要的GNU项目中经常包含源代码,包括GCC和Binutils,两者都使用它很多.但也可以将其构建为在程序中使用的动态库.例如Ubuntu有libiberty-dev包.
xmalloc记录在:https://gcc.gnu.org/onlinedocs/libiberty/Functions.html和GCC 5.2.0上,它在libiberty/xmalloc.c上实现.
PTR
xmalloc (size_t size)
{
PTR newmem;
if (size == 0)
size = 1;
newmem = malloc (size);
if (!newmem)
xmalloc_failed (size);
return (newmem);
}
void
xmalloc_failed (size_t size)
{
#ifdef HAVE_SBRK
extern char **environ;
size_t allocated;
if (first_break != NULL)
allocated = (char *) sbrk (0) - first_break;
else
allocated = (char *) sbrk (0) - (char *) &environ;
fprintf (stderr,
"\n%s%sout of memory allocating %lu bytes after a total of %lu bytes\n",
name, *name ? ": " : "",
(unsigned long) size, (unsigned long) allocated);
#else /* HAVE_SBRK */
fprintf (stderr,
"\n%s%sout of memory allocating %lu bytes\n",
name, *name ? ": " : "",
(unsigned long) size);
#endif /* HAVE_SBRK */
xexit (1);
}
/* This variable is set by xatexit if it is called. This way, xmalloc
doesn't drag xatexit into the link. */
void (*_xexit_cleanup) (void);
void
xexit (int code)
{
if (_xexit_cleanup != NULL)
(*_xexit_cleanup) ();
exit (code);
}
Run Code Online (Sandbox Code Playgroud)
正如其他人所提到的那样,非常简单:
mallocexit