Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
601 views
in Technique[技术] by (71.8m points)

architecture - What is meant by the most restrictive type in C?

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

Although machines vary, for each machine there is a most restrictive type: if the most restrictive type can be stored at a particular address, all other types may be also. On some machines, the most restrictive type is a double; on others, int or long suffices.

In their code, the union header is aligned using the type long.

What is meant by the most restrictive type? Is it perhaps the largest type (e.g., double), or is there another approach?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...