我有一个结构,其相关部分是:
typedef struct {
uint64_t *num;
...
} name;
Run Code Online (Sandbox Code Playgroud)
在大多数架构中它自然会有对齐8,但由于原因(传统原因),我需要它有对齐4,因为我可以保证后者对齐,但不能保证前者.
我发现的解决方案是添加__attribute__((packed,aligned(4)))到声明中.
我已经在godbolt.com进行了测试,它确实可以工作,并在他们拥有的每个架构上产生正确数量的负载.
GCC文档没有特别提及这种组合,而clang文档根本没有提到这些属性.
我的问题是,这是多么便携(在类似unix的环境之间)和未来的证据?
明年的海湾合作委员会/铿锵会打破整个事情吗?
我应该更喜欢#pragma pack(4)它,看起来几乎相同吗?
免责声明:以下是纯粹的学术问题; 我将此代码与任何生产系统保持至少100米的距离.这里提出的问题是任何"现实生活"案件都无法衡量的问题.
考虑以下代码(godbolt链接):
#include <stdlib.h>
typedef int (*func_t)(int *ptr); // functions must conform to this interface
extern int uses_the_ptr(int *ptr);
extern int doesnt_use_the_ptr(int *ptr);
int foo() {
// actual selection is complex, there are multiple functions,
// but I know `func` will point to a function that doesn't use the argument
func_t func = doesnt_use_the_ptr;
int *unused_ptr_arg = NULL; // I pay a zeroing (e.g. `xor reg reg`) in every compiler
int *unused_ptr_arg; // UB, gcc zeroes (thanks …Run Code Online (Sandbox Code Playgroud) 我正在寻找一个执行以下操作的程序:
./prog &pmap工具,程序和[stack]字段.这个问题不仅仅是学术性的,我正在研究内存扫描仪,我需要一个最小的例子来处理.
我能想出的最小(纯C)是:
#include <unistd.h>
int main(int argc, char **argv)
{
pause();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但是我确信这可以与一些程序集/编译器/ C奥术魔法相形见绌,因为这个程序+堆栈超过180 KB.