Creating a flexible malloc

Discuss programming topics for any language, any source base. If it is programming related but doesn't fit in one of the below categories, it goes here.
Post Reply
mankrip
Posts: 924
Joined: Fri Jul 04, 2008 3:02 am

Creating a flexible malloc

Post by mankrip »

Here's my attempt at a flexible memory allocation method:
If there's not enough RAM, the value of the desired amount is halved until malloc suceeds. The algorithm then iterates down from the previously attempted higher amount value, until the highest possible available amount value is found.
The algorithm also ensures that a minimum amount of free memory is still available for the program to use elsewhere.

However, this doesn't seem to be working. It always calls Sys_Error, which means malloc is always failing, despite the initial D_SurfaceCacheForRes value being actually valid (it works if I malloc it directly).

[edit] I've fixed the code now.

Code: Select all

	// initialize
	maxofs = D_SurfaceCacheForRes (width, height);
	vid_surfcachesize = 0;
	// iterate up
	do
	{
		minofs = maxofs - vid_surfcachesize;
		// iterate down
		do
		{
			maxofs = minofs; // before halving.
			minofs >>= 1;
			if (!(vid_surfcachesize + minofs))
			{
				Sys_Error ("Not enough RAM for surface caches\n");
				return false;
			}
		}
		while (!(vid_surfcache = (byte *)malloc (vid_surfcachesize + minofs))); // still null
		// finally allocated it, so let's free and try to reallocate a higher value.
		free (vid_surfcache);
		vid_surfcachesize += minofs; // this value is guaranteed to work now.
	}
	while ( (maxofs - minofs) > 0x0FFFFFFF); // 256 * 1024 * 1024 // should let enough free RAM to compile textures.
	// now allocate it for good.
	vid_surfcache = (byte *)malloc (vid_surfcachesize);
Last edited by mankrip on Mon Nov 22, 2021 3:39 am, edited 1 time in total.
Ph'nglui mglw'nafh mankrip Hell's end wgah'nagl fhtagn.
==-=-=-=-=-=-=-=-=-=-==
Dev blog / Twitter / YouTube
frag.machine
Posts: 2126
Joined: Sat Nov 25, 2006 1:49 pm

Re: Creating a flexible malloc

Post by frag.machine »

Hey there mankrip,

Have you considered using realloc() instead ?
I know FrikaC made a cgi-bin version of the quakec interpreter once and wrote part of his website in QuakeC :) (LordHavoc)
mankrip
Posts: 924
Joined: Fri Jul 04, 2008 3:02 am

Re: Creating a flexible malloc

Post by mankrip »

The error was in the if statement before the Sys_Error, I've fixed it now.
Ph'nglui mglw'nafh mankrip Hell's end wgah'nagl fhtagn.
==-=-=-=-=-=-=-=-=-=-==
Dev blog / Twitter / YouTube
Post Reply