Why does malloc allocate a different number of bytes than requested?
There are no guarantees that two malloc calls return blocks exactly packed together - in fact there aren't any guarantees about the result at all, except that if it's non NULL it will point to a block as least as big as the one requested.
Internally, most mallocs hold working data to help them manage the heap. For instance, those 8 bytes might contain two pointers - one pointing to the next block, and one pointing to the previous block. I don't know what those 8 bytes are because you didn't mention which OS you're running on, but it's perfectly normal for malloc to use some memory for itself behind the scenes.
Some allocators (eg on windows) provide a library function to discover block size given a pointer, however, some don't, as it's a rather esoteric feature.
The malloc
function always allocates slightly more than you ask for, in order to store some bookkeeping information. After all, when you call free()
it needs to know how big the block is.
Also, generally malloc
implementations will round the requested size up to the next multiple of 8 or 16 or some other round-ish number.
Update: The real answer to your question lies in your use of the short int
type. When doing pointer arithmetic (subtraction) between typed pointers, C and C++ return the difference in the number of things pointed to. Since you are pointing to short int
, which is two bytes in size, the value returned is half of what you are expecting.
On the other hand, malloc
always allocates a given number of bytes, no matter what you cast the result to afterward. Try this:
array=(short int*)malloc(sizeof(short int) * size);
First, Malloc makes no guarantees that two successive malloc calls return successive pointers.
Second, depending on your specific architecture, different alignment rules apply; sometimes you might ask for a single byte, but the architecture prefers allocations on 8- or 4-byte intervals.
Third, malloc needs some overhead to store how big the allocated block is, etc.
Don't make assumptions about what malloc is doing past what the documentation says!