返回的是hello world中每个字母的地址中的字符串!!
你这么试一试就明白了
char i='h';
printf("%s",&i);



帮楼主用gcc和objdump分析了一下,编译的时候为了清楚,关闭了堆栈保护,不进行优化:
gcc -O0 -fno-stack-protector -o test test.c
反汇编结果如下:
080483c4 <Get>:
80483c4: 55 push %ebp
80483c5: 89 e5 mov %esp,%ebp
80483c7: 83 ec 10 sub $0x10,%esp
80483ca: c7 45 f4 68 65 6c 6c movl $0x6c6c6568,-0xc(%ebp)
80483d1: c7 45 f8 6f 20 77 6f movl $0x6f77206f,-0x8(%ebp)
80483d8: c7 45 fc 72 6c 64 00 movl $0x646c72,-0x4(%ebp)
80483df: 8d 45 f4 lea -0xc(%ebp),%eax
80483e2: c9 leave
80483e3: c3 ret
080483e4 <main>:
80483e4: 55 push %ebp
80483e5: 89 e5 mov %esp,%ebp
80483e7: 83 e4 f0 and $0xfffffff0,%esp
80483ea: 83 ec 20 sub $0x20,%esp
80483ed: c7 44 24 1c 00 00 00 movl $0x0,0x1c(%esp)
80483f4: 00
80483f5: e8 ca ff ff ff call 80483c4 <Get>
80483fa: 89 44 24 1c mov %eax,0x1c(%esp)
80483fe: 8b 44 24 1c mov 0x1c(%esp),%eax
8048402: 89 04 24 mov %eax,(%esp)
8048405: e8 ea fe ff ff call 80482f4 <printf@plt>
804840a: c9 leave
804840b: c3 ret
804840c: 90 nop
804840d: 90 nop
804840e: 90 nop
804840f: 90 nop
可以看出hello world是存在于栈中的,涉及的命令是:
80483ca: c7 45 f4 68 65 6c 6c movl $0x6c6c6568,-0xc(%ebp)
80483d1: c7 45 f8 6f 20 77 6f movl $0x6f77206f,-0x8(%ebp)
80483d8: c7 45 fc 72 6c 64 00 movl $0x646c72,-0x4(%ebp)
例如:0x68 0x65 0x6c 0x6c 0x6f对应ascII中的"hello“
所以Get函数返回的是栈中的一个地址,而这个地址处的内容在调用printf的时候被覆盖了,所以打印出奇怪的内容。

char *Get(void)
{
char p[]="hello world";
char *a;
strcpy(a,p);
return a;
}
这个函数中初始化的字符数组是局部变量,建立在系统的栈上面,一旦函数退出,栈就被恢复,所以“hello worl”也就不复存在了~!

回复
有奖活动 | |
---|---|
【有奖活动】分享技术经验,兑换京东卡 | |
话不多说,快进群! | |
请大声喊出:我要开发板! | |
【有奖活动】EEPW网站征稿正在进行时,欢迎踊跃投稿啦 | |
奖!发布技术笔记,技术评测贴换取您心仪的礼品 | |
打赏了!打赏了!打赏了! |
打赏帖 | |
---|---|
基于MSPM0L1306的MODBUS-RTU协议通讯实验被打赏50分 | |
每周了解几个硬件知识+485硬件知识分享被打赏10分 | |
【换取手持示波器】树莓派PICOW网页烟花被打赏18分 | |
【换取手持示波器】树莓派PICO逻辑分析仪被打赏16分 | |
【分享评测,赢取加热台】教你五分钟本地部署蒸馏版本的DeepSeekR1-7B被打赏12分 | |
【换取手持示波器】蓝牙音箱更换电池被打赏8分 | |
【换取手持示波器】鼠标更换微动开关被打赏10分 | |
【我要开发板】4.传感器移植被打赏50分 | |
【换取手持数字示波器】RISC-VGCC使用-fno-omit-frame-pointer编译选项实现栈回溯被打赏29分 | |
【分享评测,赢取加热台】+开关电源简述被打赏7分 |