Malloc call error but works elsewhere

I wonder if anyone can figure this out ...

My program crashes into this call:

void subtract(data* array,data* inverse,int a, int b, int q, int n) { data* arraytomultiply; arraytomultiply = (data *)malloc(sizeof(data*) * n); 

If the data just contains int (this is for convenience when switching types later)

 typedef struct { int value; }data; 

I tried a lot of messing around with changing pointers here, as I'm not sure about them at all, but to no avail.

The strange thing is, the same call works much earlier in the program, I assign values ​​to it and I can print them and that's it ..:

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

One thing that can be useful (although I don’t know why) is that when it works earlier, it is used during the void function, whereas when it fails in a function called inside the algorithm. but I don’t see how this can affect him at all, given what I'm trying to do, it’s not using any arguments, etc.

Any ideas?

+3
source share
4 answers

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

+5
source

You highlight m * n data * elements, not data . If you need an array of pointers to data , then what you are doing in malloc() is correct, but this 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 see if it didn't work or failed!

 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 every reason to fail. But, when you said, it worked earlier but crashed later did a few experiments. I tried your code snippet and found that it works for me. I tried many times, but it never crashed. I am puzzled and I asked 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!

+1
source

You are all right, but in any case, I wonder why this is happening.

Interesting because it is expected that the size of data (as defined above) will be less than or equal to the size of data* .

0
source

When malloc crashes, this usually happens because you messed up the structures that it uses to track memory on the heap elsewhere. Is your program multithreaded? Try running it with helgrind or drd (both valgrind tools). They can help you track race conditions, insecure data access, or other streaming issues.

0
source

Source: https://habr.com/ru/post/1389699/


All Articles