gpt4 book ai didi

Linux 上的 C 内联汇编,将字符串从堆栈写入标准输出

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:01:27 25 4
gpt4 key购买 nike

如何从堆栈中将字符串(例如“Hello”)写入标准输出?没有数据段,也就是说。

void main() {
__asm__(
"movl $0x4, %eax \n\t"
"movl $0x1, %ebx \n\t"
// put "Hello" on the stack and load its address into %ecx
"movl $0x5, %edx \n\t"
"int $0x80 \n\t"

"movl $0x1, %eax \n\t"
"movl $0x0, %ebx \n\t"
"int $0x80 \n\t"
);
}

提前致谢

最佳答案

答案一:

int main()
{
const char* string = "hello"; // string is not in a data segment, it's in the text segment
fputs(string, stdout);
return 0;
}

答案2:

int main()
{
char[6] string = "hello"; // Space for string allocated on stack
fputs(string, stdout);
return 0;
}

对于 gcc,第二个答案似乎生成以下内容:

main:      
leal 4(%esp), %ecx
andl $-16, %esp
pushl -4(%ecx)
pushl %ebp
movl %esp, %ebp
pushl %ecx
subl $36, %esp
movl $1819043176, -10(%ebp) ;<< hell
movw $111, -6(%ebp) ;<< o\0
movl stdout, %eax
movl %eax, 4(%esp)
leal -10(%ebp), %eax
movl %eax, (%esp)
call fputs
movl $0, %eax
addl $36, %esp
popl %ecx
popl %ebp
leal -4(%ecx), %esp

这显然只使用堆栈。

关于Linux 上的 C 内联汇编,将字符串从堆栈写入标准输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3263555/

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