I'm not sure to understand your problem but why don't you try something like:
#define MEM_BUFFER 4096
#define size_t unsigned int
char heap_space[MEM_BUFFER] = {0};
struct myblock
{
struct myblock *next;
struct myblock *prev;
int size;
char *buffer;
};
void *malloc(size_t size)
{
struct myblock *tmp = heap_space;
if (tmp != 0) // != 0 since NULL is in stdlib
while (tmp->next != 0)
tmp = tmp->next;
struct myblock *new_elem = tmp; //your question I guess
new_elem->prev = tmp;
new_elem->size = size;
new_elem->buffer = new_elem + sizeof(*new_elem);
new_elem->next = new_elem->buffer + new_elem->size;
return (new_elem->buffer);
}
int main()
{
char *str1 = malloc(10);
char *str2 = malloc(10);
strcpy(str1, "Hello");
strcpy(str2, "World");
printf("%s %s\n", str1, str2);
}
You should just think your memory in a different way I guess, where inside your heap_space you can have many things.
If you don't understand something please ask.
You should also use void * and unsigned int instead of int
Furthermore you still have some stuff to do:
- Check if the size required is available in your array
- Give a little more space in case you want to implement your
realloc
- Implement your free function
And if you are on linux, you should try to use brk/sbrk instead of having your 'heap space'. But the greatest thing is to run 'real' programs with your own malloc (using LD_PRELOAD)
reinterpret_cast??