开发者

malloc exception in VS

i am trying to allocate memory for a 2 dimensional array using c and i am getting an exception in visual studio 2008.

int Count=16383,N=14;
char **result=(char**)malloc(sizeof(char)*Count);
for(int i=1;i<=Count;i++)       
    result[i] = 开发者_如何转开发(char*)malloc(sizeof(char)*N);  

Unhandled exception at 0x012e1692 in combination.exe: 0xC0000005: 
Access violation writing location 0x00590000

the exception takes place when i is 11272 and i can't understand why!


char **result=(char**)malloc(sizeof(char)*Count);

should be

char **result=(char**)malloc(sizeof(char*)*Count);


This is why in C code you should never cast the result of malloc and why you should not use type names in sizeof. You memory allocations should have looked as follows

char **result = malloc(Count * sizeof *result);

for(int i = 0; i < Count; ++i)       
    result[i] = malloc(N * sizeof *result[i]);  

That way the sizes would be automatically calculated correctly, and your memory allocations would be type-independent.

P.S. You said you are using C. Why is your question tagged [C] and [C++] at the same time?


First of all, don't cast the result of malloc. It's completely unnecessary, obfuscates your code, and can cover up a potentially serious bug if you've forgotten to include a header that provides a proper prototype (or at least declaration) of malloc.

Second, don't multiply by sizeof(char), or sizeof(whatever_type) -- instead multiply by sizeof(*destination_variable). Finally, instead of using <= in your loop, use <. The normal idiom for traversing an array in C is for (i=0; i<array_size; i++):

int Count=16383,N=14;

char **result = malloc(Count * sizeof(*result));

for(int i=1;i<Count;i++)
    result[i] = malloc(N * sizeof(*result[i]));

This not only fixes the problem you encountered, but prevents it from happening again in the future. For example, let's consider starting from code like this:

char **result = malloc(Count * sizeof(char *));

for(int i=1;i<Count;i++)
    result[i] = malloc(N * sizeof(char));

Now, you've been told you need to support Unicode, so you change result from char ** to wchar_t **:

wchar_t **result = malloc(Count * sizeof(char *);

for(int i=1;i<Count;i++)
    result[i] = malloc(N * sizeof(char));

But now you have a problem again -- you need to change the sizeof(char) to sizeof(wchar_t). You really should also change the sizeof(char *) to sizeof(whcar_t *), though chances are pretty good that the two will be the same, so you'll be able to get away with that discrepancy.

If you use sizeof(*result) and sizeof(*result[i]), a change like this gets handled automatically -- everything else is based on the type of result, so when you change that type, the other sizes are automatically adjusted to match.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜