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
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.
Shouldn't that be sizeof(data) instead of sizeof(data*) since you're allocating space for data structures?
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!
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*
.