Archived

This topic is now archived and is closed to further replies.

malloc & free problem

Recommended Posts

tordyvel    128
This code crashes when I run it but I can''t find anything wrong. If I remove the free(Data); line or the loops that fills the array it doesn''t crash. please help me.

USHORT *Data;

int iWidth = 50;
int iHeight = 50;

int newSize = iWidth*iHeight;

Data = (USHORT*)malloc(newSize);

for(y=0;y<iHeight;y++)
for(int x=0;x<iWidth;x++)
Data = (USHORT*)5000;
if(Data)
free(Data);
Data = NULL;


Share on other sites
Guest Anonymous Poster
You''re missing either [] after Data, or a * before it.

Share on other sites
Colin Jeanne    1114
Instead of Data = (USHORT*)5000 you could write Data[x + y * iWidth] = 5000;

I will not make a list of links... I will not make a list of links... I will not make a list of links...

Share on other sites
Guest Anonymous Poster
Or, more precisely:

Data = (USHORT*)5000;

should maybe be:
Data[ (y*iWidth) + x ] = 5000;
-or-
*Data++ = 5000;

Depends on what you are trying to do.

Share on other sites
DerekSaw    243
...your code changes where Data points to. Instead of Data pointing to the memory you just allocated for it, you change it to point else where (5000?). And when you free it, you are freeing something that is not even allocated.

Just try any of the suggested solution should correct the problem.

[edited by - DerekSaw on June 6, 2002 10:12:34 PM]

Share on other sites
IndirectX    122
Besides, you should be malloc''ing newSize*sizeof(USHORT), because malloc''s parameter is the number of bytes to allocate, not the number of items in an array as it is for new.