I'm trying to make a function that allocates memory in blocks and than is able to assign a memory pointer for different structures linked together.
#define MEMSIZE 50*1024*1024*sizeof(char)
#include "globals.h"
void *AddBlock(void){
memstart = (char*) calloc(1,MEMSIZE);
if(memstart==NULL){
printf("Hittade inte minne...:\n");
getchar();
throw 1;
}
memptr = memstart;
return memstart;
}
void* GetSpace(size_t size){ //gör nytt block eller putta fram pekaren
//makes a new block or increases ptr
void *tmp = NULL;//where the data should be stored
if(( memptr+size+1 >= memstart+MEMSIZE) )
tmp = AddBlock();
else
{
tmp = memptr;
memptr+=size;
}
return tmp;
}
void InitMem(void){ //init of memory globals
AddBlock();
}
memptr
and memstart
are extern char*
. memstart
is start of block and memptr
is where you are at.
InitMem
is run in main
upon start.
globals .h
extern char *memstart;
extern char *memptr;
globals .cpp
char *memstart;
char *memptr;
E.g. struct Node* TheNode = GetSpace(sizeof(struct Node));
But the code works really bad and gives a lot of glitches in the program.
Is there any common way to do this? When I allocate memory for each structure with malloc there are way to much overhead and that's a huge deal since the tree consists of millions of nodes.
This leg of code has a problem
if(( memptr+size+1 >= memstart+MEMSIZE) )
tmp = AddBlock();
because it is not advancing memptr by size.