title: How to get memory block length after malloc?
body: <p>I thought that I couldn't retrieve the length of an allocated memory block like the simple <code>.length</code> function in Java. However, I now know that when <code>malloc()</code> allocates the block, it allocates extra bytes to hold an integer containing the size of the block. This integer is located at the beginning of the block; the address actually returned to the caller points to the location just past this length value. The problem is, I can't access that address to retrieve the block length.</p>
  
  <pre><code>#include &lt;stdlib.h&gt;
  #include &lt;stdio.h&gt;
  int main(void)
  {
          char *str;
          str = (char*) malloc(sizeof(char)*1000);
          int *length;
          length = str-4; /*because on 32 bit system, an int is 4 bytes long*/
          printf("Length of str:%d\n", *length);
          free(str);
  }
  </code></pre>
  
  <p>**Edit: 
  I finally did it. The problem is, it keeps giving 0 as the length instead of the size on my system is because my Ubuntu is 64 bit. I changed str-4 to str-8, and it works now.</p>
  
  <p>If I change the size to 2000, it produces 2017 as the length. However, when I change to 3000, it gives 3009. I am using GCC.</p>