malloc & free problem

Started by
5 comments, last by tordyvel 21 years, 10 months ago
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;		
  
Advertisement
You''re missing either [] after Data, or a * before it.
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...
Invader''s Realm
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.
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]
"after many years of singularity, i'm still searching on the event horizon"
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.
---visit #directxdev on afternet <- not just for directx, despite the name
Thanks for all your help!
I didn''t know that thing about malloc and new

This topic is closed to new replies.

Advertisement