开发者

C, calloc automatically takes care of overflow?

matrix* make_matrix(size_t width, size_t height, size_t k, options opt){

    matrix *m= malloc(sizeof(matrix));
    if(m==NULL) return NULL;

    m->width = width;
    m->height = height;
    m->k = k;

    /*
    Since m->data is a int **, it points to int *, 
    so I have to allocate a number of int *-sized objects to store in it.
    */
    //m->data = malloc(sizeof(int *)*height);
    m->data = calloc(height, sizeof(int*));

    if(m->data == NULL){
        free(m);
        return NULL;
    }

    for(size_t i=0; i < height; i++){
        //m->data[i] = malloc(sizeof(int)*width);
        m->data[i] = calloc(width, sizeof(int));

        if(m->data[i] == NULL){
            for(size_t j = 0; j < i; j++) free(m->data[j]);
            free(m->data);
            free(m);
            return 0;
        }
        /*
        for(size_t j = 0; j < width; j++){
            m->data[i][j] = 0;
        }*/
    }

    return m;
}

I am generating an 2d array and I used malloc instead of calloc. And it turned out that this is going to be a sparse matrix where most of the elements will be zero. So I decided to use calloc. My question is that do I stil need to keep the if statement

        if(m->data[i] == NULL){
            for(size_t j = 0; j < i; j++) free(m->data[j]);
            free(m->data);
         开发者_StackOverflow中文版   free(m);
            return 0;
        }

I wrote this because malloc doesn't take care of the stack over flow issue so in case of it fails then I have to free those blocks in reverse order. Do I still keep this code with calloc?


Yes. calloc can (and will) fail just as hard as malloc.


This is not a case of "stack overflow", as you are allocating objects on the heap.

The if is required for both malloc and calloc. What it does is that if you fail half-way through your allocation, it will delete the parts you already have allocated. The order is not important.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜