Why does allocated memory is different than the size of the string?

前端 未结 2 1279
你的背包
你的背包 2021-01-29 08:30

Please consider the following code:

char    **ptr;

str = malloc(sizeof(char *) * 3); // Allocates enough memory for 3 char pointers
str[0] = malloc(sizeof(char)         


        
相关标签:
2条回答
  • 2021-01-29 09:08

    There at least two reasons malloc() may return memory in the manner you've noted.

    1. Efficiency and peformance. By returning blocks of memory in only a small set of actual sizes, a request for memory is much more likely to find an already-existing block of memory that can be used, or wind up producing a block of memory that can be easily reused in the future. This will make the request return faster and has the side effect of limiting memory fragmentation.
    2. Implications arising from the memory alignment requirements 7.22.3 Memory management functions of the C Standard states "The order and contiguity of storage allocated by successive calls to the aligned_alloc, calloc, malloc, and realloc functions is unspecified. The pointer returned if the allocation succeeds is suitably aligned so that it may be assigned to a pointer to any type of object with a fundamental alignment requirement ..." Note the italicized part. Since the malloc() implementation has no knowledge of what the memory is to be used for, the memory returned has to be suitably aligned for any possible use. This usually means 8- or 16-byte alignment, depending on the platform.
    0 讨论(0)
  • 2021-01-29 09:22

    Three reasons:

    (1) The string "ABC" contains 4 characters, because every string in C has to have a terminating '\0'.

    (2) Many processors have memory address alignment issues that make it most efficient when any block allocated by malloc() starts on an address that is a multiple of 4, or 8, or whatever the "natural" memory size is.

    (3) The malloc() function itself requires some memory to store information about what has been allocated where, so that free() knows what to do.

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