malloc错误检查方法

roc*_*797 8 c malloc

我已经看到了几种不同的方法来进行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)

Mag*_*gix 5

当你发现一个错误malloc(),calloc()realloc()(即它们返回NULL指针),errno设置.然后,您可以使用标准函数perror()打印错误,而无需进行自己的格式化.请注意,它会自动打印到stderr,无需为此烦恼.

此外,如果您的应用程序将错误视为致命错误,则必须结束该过程.如果您的代码位于main()函数中,则使用return EXIT_FAILURE;正常,exit(EXIT_FAILURE);如果没有则使用.在这种情况下,建议不要使用您自己的返回代码退出.如果错误不被视为致命错误,那么由您决定如何处理它.

还请注意,当realloc()失败并返回时NULL,旧指针仍然有效,因此必须free在离开之前为d.

  • errno*可能由malloc失败设置*.检查malloc的返回值是了解它是否失败的唯一保证方式. (2认同)

Jon*_*art 5

这个包装怎么样:

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在任何地方,不必担心错误检查。

没有编写许多程序来妥善处理内存分配失败,并且该解决方案仅适用于那些应用程序。如果你的应用能够后内存分配失败继续,那么你可能就不会问这个问题。

  • @Magix 当您的应用程序内存不足时,内存泄漏是您最不用担心的。无论如何,当进程退出时,它的所有内存都会返回到内核。 (2认同)
  • @Chrono 谢谢,改为%zu。但同样,在中止之前释放内存是没有意义的。 (2认同)

Faw*_*zan 2

重要的不是你如何检查错误,而是你如何处理错误。在所有情况下,您可以看到使用的通用代码是

if (ptr == NULL) {....}

当你遇到返回值为 时NULL,你之后做什么是你个人的选择。有些开发人员甚至喜欢assert()这个程序。

同时 gcc 会为你设置 errno。因此,您可以使用它来获取更多详细信息并使用它。

总之,您可以为您的计划做最适合您的事情。