title: custom memory allocator
body: <p>I wrote a custom memory allocator.  It has 2 restrictions that I want to remove so it works like malloc/free.</p>
  
  <p>1.)  The mem_free call requires a cast to an unsigned char * for its input parameter.  I would like it to take a pointer of any type.  How can this be done?</p>
  
  <p>2.)  The memory allocator I wrote allocates a block of memory to the front of the buffer and it also writes its size.  The free function removes the last block of allocated memory in the buffer.  So the order of the malloc/free calls matter or it will not work.    How can I remove this restriction?  </p>
  
  <p>want to be able to do this:</p>
  
  <pre><code>char* ptr1 = mem_alloc(10);
  char* ptr2 = mem_alloc(4);
  
  mem_free(ptr1);
  mem_free(ptr2);
  </code></pre>
  
  <p>have to do this now:</p>
  
  <pre><code>char* ptr1 = mem_alloc(10);
  char* ptr2 = mem_alloc(4);
  
  mem_free(ptr2);
  mem_free(ptr1);
  </code></pre>
  
  <p>code:</p>
  
  <pre><code>unsigned char* mem_alloc(unsigned int size) {
      unsigned int s;
      if( (size + MEM_HEADER_SIZE)  &gt; (MEM_MAX_SIZE - mem_current_size_bytes) ) {
          return NULL;
      }
      if(is_big_endian() == 0) {
          s = (mem_buff[3] &lt;&lt; 24) + (mem_buff[2] &lt;&lt; 16) + (mem_buff[1] &lt;&lt; 8) + mem_buff[0];
      } else {
          s = (mem_buff[0] &lt;&lt; 24) + (mem_buff[1] &lt;&lt; 16) + (mem_buff[2] &lt;&lt; 8) + mem_buff[3];
      }
      memcpy(mem_buff + mem_current_size_bytes, &amp;size, sizeof(unsigned int));
      unsigned char* result = mem_buff + (mem_current_size_bytes + MEM_HEADER_SIZE);
      mem_current_size_bytes += MEM_HEADER_SIZE + size;
      return result;
  }
  
  void mem_free(unsigned char* ptr) {
      unsigned int i,s;
      for(i=0; i&lt;mem_current_size_bytes; i++) {
          if( (char*)ptr == (char*)(mem_buff + i) ) {
              if(is_big_endian() == 0) {
                  s = (*(ptr - 1) &lt;&lt; 24) + (*(ptr - 2) &lt;&lt; 16) + (*(ptr - 3) &lt;&lt; 8) + *(ptr - 4);
              } else {
                  s = (*(ptr - 4) &lt;&lt; 24) + (*(ptr - 3) &lt;&lt; 16) + (*(ptr - 2) &lt;&lt; 8) + *(ptr - 1);
              }
              mem_current_size_bytes-=s;
              mem_current_size_bytes-=MEM_HEADER_SIZE;
              break;
          }
      }
  }
  </code></pre>