Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy does malloc allocate a different number of bytes than requested?
    text
    copied!<p>I have this piece of code</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdint.h&gt; #include &lt;string.h&gt; int main(){ void *a, *b; a = malloc(16); b = malloc(16); printf("\n block size (for a): %p-%p : %li", b, a, b-a); a = malloc(1024); b = malloc(1024); printf("\n block size (for a): %p-%p : %li", b, a, b-a); } </code></pre> <p>Shouldn't this print the last allocated block size (16 or 1024)? It instead prints 24 and 1032, so the amount of memory allocated seems to have 8 extra bytes.</p> <p>My problem is (before making this test case) that I do <code>malloc()</code> in a function (1024 bytes), and return the allocated result. When checking the block size on the function return I get 516 blocks... and I don't understand why. I guess this might be the reason for the memory corruption that occurs after doing some processing on the allocated buffers:)</p> <p><b>Edit:</b> I've seen <a href="https://stackoverflow.com/questions/232691/array-size-from-pointer-in-c">How can I get the size of an array from a pointer in C?</a> and seems to ask the same thing, sorry for reposting.</p> <p>I've redone my example to my more specific code:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdint.h&gt; #include &lt;string.h&gt; short int * mallocStuff(long int number, short int base){ short int *array; int size=1024; array=(short int*)calloc(1,size); //array=(short int*)malloc(size); return array; } int main(){ short int **translatedArray; translatedArray=malloc(4*sizeof(short int)); int i; for(i=0;i&lt;4;i++){ translatedArray[i]=mallocStuff(0,0); if(i&gt;0) printf("\n block size (for a): %p-%p : %i", translatedArray[i], translatedArray[i-1], translatedArray[i]-translatedArray[i-1]); } return 0; } </code></pre> <p>And the output is</p> <pre><code> block size (for a): 0x804a420-0x804a018 : 516 block size (for a): 0x804a828-0x804a420 : 516 block size (for a): 0x804ac30-0x804a828 : 516 </code></pre> <p>According to the above post that is bigger than 1024. Am I wrong?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload