Archived

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

tordyvel

malloc & free problem

Recommended Posts

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 this post


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

The line that reads:
Data = (USHORT*)5000;

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

Depends on what you are trying to do.

Share this post


Link to post
Share on other sites
Your problem started when....
...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 this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites