Malloc call crashing, but works elsewhere

前端 未结 4 1273
春和景丽
春和景丽 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:23

    When malloc crashes, it is usually because you have messed up the structures it uses to track memory on the heap somewhere else. Is your program multi-threaded? Try running it with helgrind or drd (both valgrind tools). These can help you track down race conditions, unprotected data accesses, or other threading issues.

    0 讨论(0)
  • 2020-12-21 06:29

    Shouldn't that be sizeof(data) instead of sizeof(data*) since you're allocating space for data structures?

    0 讨论(0)
  • 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!

    0 讨论(0)
  • 2020-12-21 06:36

    You all are right, but anyhow I wonder why this crashes.

    I wonder because the size of data (as defined above) is expected to be less or equal to the size of data*.

    0 讨论(0)
提交回复
热议问题