Hi I have this question: Why when I\'m allocating memory with malloc for a float array, it allocate more space that i\'m requesting? For example in this code i\'m trying to
It's not unlikely that, depending on allocation algorithm, that more is allocated than you request. However, accessing that memory is undefined behavior.
When calling malloc
, additional space may used to store metadata about the allocated block, such as its size and information about other allocated blocks. Sometimes the implementation prefers allocated blocks to be at specific intervals (e.g., multiples of 4 or 8 bytes). However, you shouldn't depend on the amount of space being consistent each time you call malloc
; use only what you have specifically requested or you may be overwriting other important information.
See the answers to the following questions for more information:
I would not be surprised if allocating heap memory does not fall into specific processor rules that addresses must be aligned on a long, quad, or other boundary.
So, if you requested 100 bytes of heap space, the OS may return more than you requested to satisfy alignment requirements of the processor. However, accessing more than the 100 bytes is considered undefined and can and probably will result in a lot of strange behavior you do not want.
You can only get a segmentation fault if a read or write falls in the wrong page. A page is typically 4KiB.
The malloc()
system call may reserve a bit more space than requested, and it reserves a few words of memory before the block for book-keeping, but that your program does not get killed when accessing fk_array[15]
does not mean that it did not access outside the block reserved for it. It probably did, the OS just didn't notice it. If you had allocated another array after allocating fk_array
, you would have had a chance to notice that it was changing.