dynamic allocation

From: meital (m_k_at_hotmail.com)
Date: 10/31/04


Date: Sat, 30 Oct 2004 19:58:11 -0400

I need to implement these functions:

void *malloc(int size);
void free(void* p);

using the functions below:

void* malloc_os(int size);
void free_os(int size, void* p);

the problem is that free_os can free only
the exact size of memory which was allocated
to p by malloc_os.

my idea was to define a struct, and for
each allocation, the number of bytes allocated
to the pointer, will be saved in the struct.

struct ptr
{
   void* pointer;
   int size;
}

the implementation should be as follows:

void* malloc(int size)
{
   return malloc_os(size);
}

void free (void* p)
{
  free_os( ((ptr*)p).size, ((ptr*)p).pointer);
}

main
{
  struct ptr m;
  int n_bytes = 9;

  m.p = (void*)malloc(size);
  m.size = n_bytes;
  free(&m);
}

any other suggestions?



Relevant Pages