I\'m trying to implement my own version of malloc, calloc, realloc, and free. Th
ID: 3529763 • Letter: I
Question
I'm trying to implement my own version of malloc, calloc, realloc, and free. This is what I have so far. I've been trying to debug it for hours but I need help. I know my logic probably isn't completely right. I'm having problems with tMemory, conflicting types, chunks not being declared in a function. Could someone please help me with this? Am i putting information in the functions that should be in main? Am I using the typedef correctly? #include #include #define NUM_XS 1000 #define NUM_S 400 #define NUM_M 150 #define NUM_L 70 #define NUM_XL 30 #define SIZE_XS 30 #define SIZE_S 50 #define SIZE_M 120 #define SIZE_L 250 #define SIZE_XL 800 #define NUM_SIZES 5 #define FALSE 0 #define TRUE 1 tMemory initializeMemory(void); tMemory *mcshMalloc(int size); tMemory *mcshCalloc(tMemory p, int size); tMemory *mcshRealloc(void *ptr, int size); tMemory *mcshFree(tMemory p, void *ptr); struct tMemory; int main (void) { } typedef struct { int num; int size; char *start; char *end; char *available; }tMemory; tMemory initializeMemory(void) { char spaceXS[NUM_SIZES*SIZE_XS]; char spaceS[NUM_S*SIZE_S]; char spaceM[NUM_M*SIZE_M]; char spaceL[NUM_L*SIZE_L]; char spaceXL[NUM_XL*SIZE_XL]; char aXS[NUM_XS]; tMemory chunks[NUM_SIZES]; int first = 50; chunks[0].num = NUM_XS; chunks[0].size = SIZE_XS; chunks[0].start = spaceXS; chunks[0].end = ( spaceXS + NUM_XS * SIZE_XS - 1 ); chunks[0].available = aXS; } tMemory *mcshMalloc(int size) { int i, j; int done = 0; static int first = 1; void *retVal = NULL; if (first) { initializeMemory(); } for( i=0; i<= chunks[i].size) { for( j=0; j< chunks[i].num ) break; } } } tMemory *mcshCalloc(int size) { int j; void *retVal = mcshMalloc(int size); if( retVal != NULL ) { for( j=0; j< minsize) minsize = size; // Copy the memory, free the old block and return the new block. memcpy (retVal, ptr, minsize); mcshFree (ptr) } return retVal; } tMemory *mcshFree(void *ptr) { int i, j; if ( (chunks[i].start <= ptr ) && ( ptr < chunks[i].end ) ) { j = (ptr - chunks[i].start) / chunks[i].size; chunks[i].available[j] = TRUE; } }Explanation / Answer
uint8_t* p;
uin8_t p_size = 0;
for(;;) {
if( Wire.available() ) {
// Increase pointer memory
uint8_t* np = (uint8_t *) realloc( p, sizeof(uint8_t) * (p_size + wire.available()) );
if( np != NULL ) { p = np; }
[ do random stuff with data at *p ]
[ call realloc() to shrink *p after data has been processed ]
[ free() what ever needs to be freed ]
}
}
//Placement new/delete
void *operator new( size_t size, void * ptr ){ return ptr; }
void operator delete( void * ptr, void *ptr2 ){ return; }
struct Obj{
int i_Something;
bool b_SomethingElse;
};
void setup( void ){
//Allocate data
void *v_Data = operator new( ( size_t ) ( sizeof( Obj ) * MAX_ITEMS ) );
//Represent allocation as an arraoy of Obj
Obj *o_Array = ( Obj* ) v_Data;
//Construct some objects in the allocation.