【发布时间】:2016-01-27 00:53:53
【问题描述】:
我见过几种不同的 malloc 错误检查方法。一种方式比另一种更好吗?某些退出代码是否比其他代码更好?使用带有 stderr 的 fprintf 是否比使用 printf 语句更好?使用返回而不是退出更好吗?
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL)
{
printf("Error! memory not allocated.");
exit(1);
}
res = malloc(strlen(str1) + strlen(str2) + 1);
if (!res) {
fprintf(stderr, "malloc() failed: insufficient memory!\n");
return EXIT_FAILURE;
}
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL)
{
printf("Error! memory not allocated.");
exit(-1);
}
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL)
{
printf("Error! memory not allocated.");
exit(EXIT_FAILURE);
}
char *ptr = (char *)malloc(sizeof(char) * some_int);
if (ptr == NULL) {
fprintf(stderr, "failed to allocate memory.\n");
return -1;
}
char* allocCharBuffer(size_t numberOfChars)
{
char *ptr = (char *)malloc(sizeof(char) * numberOfChars);
if (ptr == NULL) {
fprintf(stderr, "failed to allocate memory.\n");
exit(-1);
}
return ptr;
}
【问题讨论】:
-
错误应写入标准错误。当出现错误退出时,退出状态应该是非零的。如果 malloc 失败应导致致命错误并立即退出,请考虑将其包装在报告错误并退出的函数中,这样您就不必检查代码中的返回值。
-
这本书现已绝版,但 Richard Heathfield 等人的“C Unleashed”有一章有趣的章节介绍了您可以用来尝试从
malloc恢复的策略失败。文字处理器的用户不希望应用程序仅仅因为他们正在尝试的操作遇到内存资源限制而崩溃。至少,如果有一些相关的状态概念,也许状态可以在退出之前以某种方式保存。不要认为malloc失败会自动终止您的程序。 -
这与 malloc 具体无关,是吗?很多事情都可能失败。
-
@rockstar797 如果您的问题得到解决,请不要忘记添加一个已接受的答案 ;-)