title: How to find how much space is allocated by a call to malloc()?
body: <p>I'm trying to write a size function like this:</p>
  
  <pre><code>size(void *p,int size);
  </code></pre>
  
  <p>Which would return the size of an array which is pointed to by p. For example:</p>
  
  <pre><code>Int *a = malloc((sizeof(int)*100));
  size(a,sizeof(int)); // this should return 100
  </code></pre>
  
  <p>I think this is possible because if I recall, malloc keeps track of the space allocated in some header bytes. </p>
  
  <p>Here's what I have so far:</p>
  
  <pre><code>int size(void *p, int size)
  {
    p = (unsigned int *)p - 1;
    unsigned int elements = (*(unsigned int *)p);
    return elements/size;
  }
  </code></pre>
  
  <p>Now, assuming that the size of the space allocated is in the 4 bytes before the pointer, this should return the bytes, or offset. This is where I'm a bit in the dark. I can't figure out the specifics of how malloc formats these header bytes. How does malloc pack the header bits?</p>
  
  <p>Thanks, I appreciate this. I'm sure there are things wrong with this code and it's not particularly portable and may be very system dependent, but I'm doing it for fun. </p>