c - Is it possible to pack a local variable with particular alignment?
问题描述
code:
#include <stdio.h>
int main() {
int a;
printf("%p\n", &a);
char b[10];
printf("%p\n", &b);
int c;
printf("%p\n", &c);
}
outputs:
0061fefc
0061fef2
0061feec
It is obvious that b
occupies 12 bytes memory becuase the default memory alignment makes the start address of c
is a multiple of 4. It is possible to disable the memory alignment? I know #pragma pack
can pack a structure, can it pack a local variable to make b
occupy only 10 bytes? This is an interview question that makes me interested. Any help will be appreciated!
解决方案
The C standard does not provide any facility to request relaxed alignment of objects, and there is little or no value in such a feature for independent objects (objects that are not members of a structure).
Structures are sometimes packed, using extensions to standard C, because the bytes in them need to be laid out consecutively for some specific use, such as transmitting them in a network message, or because padding in them may waste large amounts of space when a great many instances of the structure are held in memory. No such purpose occurs with a single independent object.
The char
array shown does not occupy twelve bytes. It occupies ten bytes. The other two bytes are either unused or are used by the compiler for other purposes not evident in the addresses examined. In a structure, padding bytes are reserved—held unavailable for other use—to give the desired alignment. In this situation, bytes may have been skipped to give the desired alignment, but they are not reserved for that purpose. If a two-byte object were needed, the compiler could insert it into those bytes.
The amount of stack space wasted due to alignment requirements is generally small because, unlike with structure members, the compiler is free to rearrange objects to use space efficiently. And the stack pointer generally must still satisfy alignment requirements of the application binary interface (ABI), so some space for alignment may still be needed regardless of the alignment requirements of objects on the stack.
推荐阅读
- javascript - Firestore 未在 signInSuccessWithAuthResult 内添加任何内容
- ios - SwiftUI 多模态表不会在代码中消失
- c - 在哪里放置文件以便在 C 中读取文件(“r”)
- python - API调用get方法
- javascript - Uncaught SyntaxError: Unexpected token '%', Flask error when using a separate js file
- html - 如何在悬停时为文本上的下划线设置动画并在鼠标上保持线条
- c# - 在类库中创建 EF DbContext
- python - 得到错误 IndentationError: 期望 python 代码中的缩进块
- kubernetes - 了解 GCP 监控中的 Kubernetes pod 资源利用率
- amazon-web-services - 使用无服务器框架如何使用 Cloud Watch 事件记录 Amazon S3 对象级操作