gpt4 book ai didi

c - 优化字符串散列时出现奇怪的程序集输出

转载 作者:行者123 更新时间:2023-12-01 16:09:38 24 4
gpt4 key购买 nike

当尝试创建一个编译时散列宏时,它成功了,但也有问题。所以我想如果字符串在编译时是已知的(它们是),整个散列应该被优化为一个常量。启用了优化级别 -O3 的 gcc C99 代码:

#include <stdio.h>


int main(void)
{
char const *const string = "hello";
int hash = 0;
for (unsigned char i=0; i < sizeof string; ++i)
{
hash += string[i]; //reeaally simple hash :)
}

printf("%i", hash);
return 0;
}

产生了以下汇编代码:

.LC0:
.string "hello"
.LC1:
.string "%i"
main:
sub rsp, 8
movsx eax, BYTE PTR .LC0[rip+6]
movsx edx, BYTE PTR .LC0[rip+7]
mov edi, OFFSET FLAT:.LC1
lea esi, [rax+532+rdx]
xor eax, eax
call printf
xor eax, eax
add rsp, 8
ret

虽然相同代码,我只是将“hello”更改为“hello w”,生成了这段汇编代码,它完全优化了散列:

.LC0:
.string "%i"
main:
sub rsp, 8
mov esi, 683
mov edi, OFFSET FLAT:.LC0
xor eax, eax
call printf
xor eax, eax
add rsp, 8
ret

Try it yourself

这是什么原因?这是否意味着我不能使用这种散列方式,因为它可能不会优化开销?我如何确保不会产生任何开销,有哪些替代方案?

编辑 1:我玩了一下,似乎如果字符串中的字符数是 6,如果字符数是 7,它就不会被优化掉,它会

最佳答案

sizeof 在这里是错误的。它返回 char 指针的大小而不是字符串的长度。

在您的情况下,它是一个 UB,编译器无法在您读取字符串文字边界之外时将其优化。这是一个 clang 错误,而不是功能。

如果你做得好,gcc 也会优化它

int main(void)
{
char const string[] = "hello";
int hash = 0;
for (unsigned char i=0; i < sizeof(string); ++i)
{
hash += string[i]; //reeaally simple hash :)
}

printf("%i", hash);
return 0;
}

https://godbolt.org/z/YCCNCt

关于c - 优化字符串散列时出现奇怪的程序集输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60872456/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com