Archived

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

Punika

Dynamic File Format

Recommended Posts

Punika    242
hi, i am using my own file format and now i want integrate dynamical map loading. my allocate function is like this:
  
	// Allocate memory for the maps Layers elements

	int MapLayers = 1;

	Map = (MAPTILE ***)malloc(sizeof(int **) * MapLayers);

	// Allocate memory for the maps X elements

	for(int lyr = 0; lyr < MapLayers; lyr++)
	{
		Map[lyr] = (MAPTILE **)malloc(sizeof(int*) * Header.Width);

		// Allocate memory for the maps Y elements

		for(int x = 0; x < Header.Width; x++)
		{
			Map[lyr][x] = (MAPTILE *)malloc(sizeof(int) * Header.Height);
		}
	}
  
now i have some problems with deallocating the memory so for example i can load another map? i have tried it with free but it crashed every time. can somebody please help me... Thanks Punika Punika [ Power Productions ]

Share this post


Link to post
Share on other sites
Dino    172
By the looks of things, you are trying to allocate memory for MapLayers number of layers of (Header.Width * Header.Height) size.

The main problem I see with your method is that it is allocated memory way too many times and there are way too many pointers. De-allocating a the main Map pointer does not de-allocate the other memory chunks. This is why this method is bad and it could also be why it is crashing.

Do it this way and you will avoid all those problems:

quote:

//It is assumed that Header is a struct that contains
// information on the map and the it has the
// following members:
// .Width - [IN] The width of a single layer
// .Height - [IN] The height of a single layer
// .NumLayers - [IN] The number of layers in the map.
// .LayerSize - [OUT] Set with the number of MAPTILE
// elements in the layer

int mem_needed;
MAPTILE *map_ptr;

//First calculate the memory needed per layer
Header.LayerSize = Header.Width * Header.Height;
mem_needed = Header.LayerSize * sizeof(MAPTILE);

//Allocate the memory needed for the map.
// This is the number of bytes needed per layer times the
// the number of layers.
map_ptr = (MAPTILE *)malloc(mem_needed * Header.NumLayers);

//All done, return the map memory pointer
return map_ptr;




It''s that simple. To clean up the memory resources after you are done with them, simply call:
quote:

free(pMap); //Free up the memory that pMap points to.
// This should be the entire memory chunk
// used by the map



To access the various layers in the map, use the following formula:
quote:

//Returns the pointer to the first entry in the
// layer specified by LayerIdx.
layer_ptr = pMap + (Header.LayerSize * LayerIdx);



To access an individual layer point (TileX, TileY) in the layer, use this formula:
quote:

//Returns a pointer to the MAPTILE structure at
// (TileX, TileY) in a given layer.
tile_ptr = layer_ptr + (TileY * Header.Width) + TileX;



Hope this all helps.

Share this post


Link to post
Share on other sites