How can I correctly handle malloc failure in C, especially when there is more than one malloc?

前端 未结 6 571
我在风中等你
我在风中等你 2021-02-01 02:49

Suppose this is a part of my code:

 int foo()
 {  
    char *p, *q ;
    if((p = malloc(BUFSIZ)) == NULL) {
        return ERROR_CODE;
    }
    if((q = malloc(B         


        
6条回答
  •  遥遥无期
    2021-02-01 03:30

    IF you are expecting to allocate a large number of items, it Can get messy. Try to avoid the 'goto' approach. Not because of the old 'goto is bad' ethic, but because that way really can lie madness and memory leaks.

    It's a little overkill for small numbers of malloc, but you can consider something like this approach:

    void free_mem(void **ptrs, size_t len)
    {
        for (size_t i = 0; i < len; ++i)
        {
            free(ptrs[i]);
            ptrs[i] = NULL;
        }
    }
    
    int foo(...)
    {
        void *to_be_freed[N];
        int next_ptr = 0;
        for (size_t i = 0; i < N; ++i) to_be_freed[i] = NULL;
    
        p = malloc(..);
        if (!p)
        {
            free_mem(to_be_freed,N);
            return ERROR_CODE;
        }
        to_be_freed[next_ptr++] = p;
    
        // Wash, rinse, repeat, with other mallocs
        free_mem(to_be_freed,N)
        return SUCCESS;
    }
    

    In reality, you can probably wrap malloc with something which tracks this. Put the array and array size in a structure and pass that in with the desired allocation size.

提交回复
热议问题