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, int n)
{
data* arraytomultiply;
arraytomultiply = (data *)malloc(sizeof(data*) * n);
Where data just holds an int (it's for convenience when switching types later)
typedef struct {
int value;
}data;
I've tried lots of messing around with changing the pointers here as I'm not confident on them at all, but to no avail.
The strange thing is, much earlier in the program this same call works, I assign values to it and can print them out and everything..:
data* array;
array = (data*)malloc(sizeof(data*) * m * n); // m * n entries
One thing that might be of use (though I have no idea why) is that when it works earlier it's during a void function, whereas when it crashes it's in a function called from within an algorithm. but I don't see how this could affect it at all, given what I'm trying to do isn't using any of the arguments etc...
Any ideas?
Shouldn't that be sizeof(data) instead of sizeof(data*) since you're allocating space for data structures?
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.
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 ofdata*
.You are allocating
m * n
elements ofdata *
and notdata
. If you want array of pointers todata
then what you are doing inmalloc()
is correct but that should be assigned todata **
It should be
and, you should always check the return value of
malloc()
to find whether it fails or succeeds!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!