题目
《深入理解计算机系统(原书第2版)》第3章 程序的机器级表示
(a) C code
/* This is very low-quality code.
It is intended to illustrate bad programming practices.
See Problem 3.43. */
char *getline()
{
char buf[8];
char *result;
gets(buf);
result = malloc(strlen(buf));
strcpy(result, buf);
return result;
}
(b) Disassembly up through call to gets
080485c0 <getline>:
80485c0: 55 push %ebp
80485c1: 89 e5 mov %esp,%ebp
80485c3: 83 ec 28 sub $0x28,%esp
80485c6: 89 5d f4 mov %ebx,-0xc(%ebp)
80485c9: 89 75 f8 mov %esi,-0x8(%ebp)
80485cc: 89 7d fc mov %edi,-0x4(%ebp)
Diagram stack at this point
80485cf: 8d 75 ec lea -0x14(%ebp),%esi
80485d2: 89 34 24 mov %esi,(%esp)
80485d5: e8 a3 ff ff ff call 804857d <gets>
Modify diagram to show stack contents at this point
Figure 3.32 C and disassembled code for Problem 3.43.
练习器3.43
B.修改你的图,展现调用gets的影响
解答
这个问题覆盖的问题比较广泛,例如栈帧、字符串表示、ASSCII码和字节顺序。
ASSCII码
ASCII值 | 对应的十六进制值 | 控制字符 |
---|---|---|
48 | 0x30 | 0 |
49 | 0x31 | 1 |
50 | 0x32 | 2 |
51 | 0x33 | 3 |
52 | 0x34 | 4 |
53 | 0x35 | 5 |
54 | 0x36 | 6 |
55 | 0x37 | 7 |
56 | 0x38 | 8 |
57 | 0x39 | 9 |
所以字符串“012345678901234567890123”的十六进制值为
30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33
又由于字符串是以'\0'结尾,所以完整的十六进制值为
30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 00
字节顺序
由于是大端法表示,最高有效字节在最前面,所以地址最小的存储的值是30,其次是31,依次类推。
栈帧
栈帧结构图
由于栈帧从下往上地址增加,所以缓冲区溢出以后,栈信息变为
08 04 86 00 |
---|
33 32 31 30 |
39 38 37 36 |
35 34 33 32 |
31 30 39 38 |
37 36 35 34 |
33 32 31 30 |