我已经看到了几种不同的方法来进行malloc错误检查.有一种方式比另一种更好吗?有些退出代码比其他代码更好吗?使用fprintf和stderr比使用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;
}
Run Code Online (Sandbox Code Playgroud)
当你发现一个错误malloc(),calloc()和realloc()(即它们返回NULL指针),errno设置.然后,您可以使用标准函数perror()打印错误,而无需进行自己的格式化.请注意,它会自动打印到stderr,无需为此烦恼.
此外,如果您的应用程序将错误视为致命错误,则必须结束该过程.如果您的代码位于main()函数中,则使用return EXIT_FAILURE;正常,exit(EXIT_FAILURE);如果没有则使用.在这种情况下,建议不要使用您自己的返回代码退出.如果错误不被视为致命错误,那么由您决定如何处理它.
还请注意,当realloc()失败并返回时NULL,旧指针仍然有效,因此必须free在离开之前为d.
这个包装怎么样:
void *safe_malloc(size_t n)
{
void *p = malloc(n);
if (p == NULL) {
fprintf(stderr, "Fatal: failed to allocate %zu bytes.\n", n);
abort();
}
return p;
}
Run Code Online (Sandbox Code Playgroud)
然后,只用safe_malloc在任何地方,不必担心错误检查。
没有编写许多程序来妥善处理内存分配失败,并且该解决方案仅适用于那些应用程序。如果你的应用是能够后内存分配失败继续,那么你可能就不会问这个问题。
重要的不是你如何检查错误,而是你如何处理错误。在所有情况下,您可以看到使用的通用代码是
if (ptr == NULL) {....}
当你遇到返回值为 时NULL,你之后做什么是你个人的选择。有些开发人员甚至喜欢assert()这个程序。
同时 gcc 会为你设置 errno。因此,您可以使用它来获取更多详细信息并使用它。
总之,您可以为您的计划做最适合您的事情。
| 归档时间: |
|
| 查看次数: |
10752 次 |
| 最近记录: |