Skip to main content
GameDev.net gamedev.net
🔒 Locked

malloc & free problem

Started by tordyvel Jun 6, 2002 at 9:00 PM 5 replies 200+ views
Original Post
tordyvel
tordyvel
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;		
  
Colin Jeanne
Colin Jeanne
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
DerekSaw
DerekSaw
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 n the event horizon" o
IndirectX
IndirectX
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
tordyvel
tordyvel
Thanks for all your help!
I didn''t know that thing about malloc and new

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.