Lea*_*dro 2 c string assembly gcc decimal
char a[] = "abc"; // movl $6513249, -12(%rbp)
char ab[] = "ab"; // movw $25185, -11(%rbp)
char abc[] = "a"; // movw $97, -10(%rbp)
Run Code Online (Sandbox Code Playgroud)
上面的 C 代码在汇编 (gcc -S code.c) 中表示为:
movl $6513249, -12(%rbp)
movw $25185, -15(%rbp)
movw $97, -17(%rbp)
Run Code Online (Sandbox Code Playgroud)
97 是十进制的“a”,但为什么“ab”是 25185 而“abc”是 6513249?
让我们取第一行的 32 位整数的十六进制值:
>>> hex(6513249)
'0x636261'
Run Code Online (Sandbox Code Playgroud)
这是 cba
由于处理器是小端的,因此它只是一种优化的方式来初始化一个小字符串,只需 32 位移动,而不是繁琐的逐字节复制。
这里的所有字符串都没有处理 nul-termination(movw $25185, -15(%rbp)sets aand bbut not nul-terminate),它是在你没有显示的代码中的其他地方完成的(请注意,nul-termination 字节有空间:第一个字符串在偏移量 -12,第二个字符串在偏移量 -15 处,这使得它有 3 个字节长,和最后一个相同)