Malloc call crashing, but works elsewhere

2019-01-28 09:14发布

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?

标签: c crash malloc
4条回答
爷、活的狠高调
2楼-- · 2019-01-28 09:52

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

查看更多
仙女界的扛把子
3楼-- · 2019-01-28 09:52

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.

查看更多
手持菜刀,她持情操
4楼-- · 2019-01-28 09:57

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*.

查看更多
戒情不戒烟
5楼-- · 2019-01-28 10:03

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!

查看更多
登录 后发表回答