Malloc error checking methods

I saw several different ways to check for malloc errors. Is one way better than the other? Are some exit codes better than others? Is using fprintf with stderr better than using printf? Does return use instead of exit better?

    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;
}
+4
source share
5 answers

When an error is detected with malloc(), calloc()and realloc()(that is, they return a NULL pointer), is set errno. Then you can use the standard function perror()to print the error without having to do your own formatting. Please note that it will automatically print on stderr, no need to worry about it.

, , . main(), return EXIT_FAILURE; exit(EXIT_FAILURE);, . . , , .

, , realloc() NULL, free d .

+4

:

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;
}

safe_malloc .

, , . , , , .

+3

, , , . ,

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

NULL, , , . assert() .

gcc errno. , .

, .

+1

№ 1. malloc ( realloc 's) .

№ 2. , stderr, .

№ 3. . ( .)

"" - , ( - , ).

№ 2, - ( fprintf stderr), .

+1
perror("more details"); 

(will try) to print an error (according to the errno variable) before stderr. You can use this.

static void die(const char* msg){ perror(msg); exit(1); }  

You can also save errno and translate it into BSD-style syssexits.h code, or just somehow linearly serialize it to the parent process (by exiting with errno or its linear translation).

0
source

Source: https://habr.com/ru/post/1626089/


All Articles