What is meant by the most restrictive type in C?

前端 未结 3 796
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-11 13:02

The book The C Programming Language talks about \"the most restrictive type\" in section 8.7, Example — A Storage Allocator:

A

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-11 13:47

    CPUs often require that (or work more efficiently if) certain types of data are stored at addresses that are a multiple of some (power-of-two) value. This value is called the alignment of the data. For example, a CPU might require that four-byte integers are stored at addresses that are a multiple of four (that they have four-byte alignment, or are aligned on four bytes).

    By the most restrictive type, they mean the type that has the most restrictive requirements in this area. So if e.g. long double requires eight-byte alignment on some machine, and no other type requires greater alignment than that, then the most restrictive type on that machine would be long double.

    It makes sense for malloc(3) to return addresses that satisfy the alignment requirements of the most restrictive type, since that means the returned memory can be used to store any type. malloc() doesn't know how the memory will be used, so it can't adapt.

    It's not necessarily the case that larger data types require greater alignment, though alignment requirements tend to increase with increasing size.

    (Some types of data might require even greater alignment than malloc() provides. For example, many x86 SSE instructions use data vectors that are aligned on 16 bytes, while e.g. the malloc() in glibc only guarantees eight-byte alignment. posix_memalign(3) can be used to dynamically allocate memory with even greater alignment requirements on POSIX (*nix) systems.)

提交回复
热议问题