Malloc call crashing, but works elsewhere

前端 未结 4 1279
春和景丽
春和景丽 2020-12-21 06:07

I wonder if anyone might have any insight on this...

My program is crashing on this call:

void subtract(data* array,data* inverse,int a, int b, int q         


        
4条回答
  •  无人及你
    2020-12-21 06:29

    You are allocating m * n elements of data * and not data. If you want array of pointers to data then what you are doing in malloc() is correct but that should be assigned to data **

    array = (data*)malloc(sizeof(data*) * m * n); // m * n entries
    

    It should be

    array = (data*)malloc(sizeof(data) * m * n); // m * n entries
    

    and, you should always check the return value of malloc() to find whether it fails or succeeds!

    if ((array = (data*)malloc(sizeof(data) * m * n)) == NULL) {
        printf("unable to allocate memory");
        return; // you can return your error code here!
    }
    

    Your program has all the reason to crash. But when you said, it worked earlier but crashed later made be to do some experiments. I tried your code snippet and found it working for me. I tried many a times but it never crashed. I got puzzled and I posted a question to find out why?! - It is available here Are "malloc(sizeof(struct a *))" and "malloc(sizeof(struct a))" the same?

    +1 to your question!

提交回复
热议问题