Are the elements of an array guaranteed to be stored from lower to higher addresses?

后端 未结 3 1555
遥遥无期
遥遥无期 2021-02-09 23:35

Suppose I have the following array:

int list[3]={2,8,9};
printf(\"%p,%p,%p\",(void*)&list[0],(void*)&list[1],(void*)&list[2]);

Is i

3条回答
  •  既然无缘
    2021-02-10 00:30

    From the C standard ("Section 6.2.5 Types"):

    ...An array type describes a contiguously allocated nonempty set of objects...

    Arrays will be allocated contiguously in "memory".

    What Eric and Interjay are saying, which is something I didn't consider when I initially wrote this so thank you Eric and Interjay, is that this only applies to the virtual memory addresses.

    Your machine and OS most likely use a memory management unit (MMU) which creates a virtual address space (where you are working) and maps this onto physical memory in chunk sized blocks (pages).

    So what Eric and Interjay are saying is that although the virtual addresses will be contiguous, the chunks of physical memory they map to may be at different addresses.

     Virtual               Physical
    +----------+           +----------+
    |          |           |
    | VMA pg 1 |---------->| PMA 88 (VMA1)
    |          |           |
    +----------+           +----------+
    |          |\           ...
    | VMA pg 2 | \          ...
    |          |  \         ...
    +----------+   \        ...
                 \  \       ...  big gap in physical
                  \  \      ...  memory
                   \  \     ...
                    \  \    ...
                     \  >--+----------+
                      \    |
                       \   | PMA 999 (VMA2)
                        \  |
                         >-+----------+
    

    So, for small arrays (smaller than the page size), this may be true for both VMA and PMA addresses, although most likely PMA != VMA. For arrays larger than the page size, although VMA looks contiguous, PMA may well be disjoint and out of order, as the above diagram tries to show...

    Also, I think Interjay and Eric are going a step further and saying that any C address, although contiguous in the C model, might be anywhere in memory. Although this is unlikely as most OS's implement some kind of paging to get a virtual to physical mapping, it can technically be the case I think... this was good to learn to consider, so thanks chaps :)

提交回复
热议问题