C : malloc seems to allocate more then i'm requesting (array)

前端 未结 4 1917
青春惊慌失措
青春惊慌失措 2021-01-15 22:48

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

相关标签:
4条回答
  • 2021-01-15 23:00

    It's not unlikely that, depending on allocation algorithm, that more is allocated than you request. However, accessing that memory is undefined behavior.

    0 讨论(0)
  • 2021-01-15 23:14

    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:

    • How do free and malloc work in C?
    • Why does malloc allocate a different number of bytes than requested?
    0 讨论(0)
  • 2021-01-15 23:18

    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.

    0 讨论(0)
  • 2021-01-15 23:24

    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.

    0 讨论(0)
提交回复
热议问题