DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

C Memory Manager "MemoryBlock "

07.01.2005
| 7170 views |
  • submit to reddit
        
//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com

#ifndef __MEMORYBLOCK__
#define __MEMORYBLOCK__


//-- includes -----------------------------------------------
#include <stdio.h>
#include <stdlib.h>



//-- data types ---------------------------------------------
typedef struct _MemoryBlock {
	void *data;
	size_t capacity, used, dataSize;
}* MemoryBlock;



//-- functions ----------------------------------------------
MemoryBlock getMemoryBlock( register const size_t dataSize, register const size_t initialSize ){

	MemoryBlock mb = (MemoryBlock)malloc( sizeof( struct _MemoryBlock ) );
	
	if( mb ) {
		mb->used = 0;
		mb->data = NULL;
		mb->dataSize = dataSize;
		mb->capacity = initialSize && ( mb->data = (void *)malloc( initialSize * dataSize ) ) ? initialSize : 0;
	}
	return mb;
}

void freeMemoryBlock( register const MemoryBlock mb ){
	free( mb->data );
	free( mb );
}

int resizeMemoryBlock( register const size_t newSize, register const MemoryBlock mb ){

	void *newData = (void *)realloc( mb->data, newSize * mb->dataSize );

	if( newData ){
		mb->data = newData;
		return mb->capacity = newSize;
	}
	return 0;
}

int growMemoryBlock( register const MemoryBlock mb ){

	size_t delta = mb->capacity > 64 ? mb->capacity / 4 : mb->capacity > 8 ? 16 : 4;
	void *newData = (void *)realloc( mb->data, ( mb->capacity + delta ) * mb->dataSize );

	if( newData ){
		mb->data = newData;
		return mb->capacity += delta;
	}
	return 0;
}

int growExMemoryBlock( register const size_t neededBlocks, register const MemoryBlock mb ){
	while( mb->used+neededBlocks > mb->capacity )
		if( !growMemoryBlock( mb ) )
			return 0;
	return 1;
}

int incMemoryBlock( register const MemoryBlock mb ){
	return  mb->used+1 <= mb->capacity || growMemoryBlock( mb );
}

#endif