C語言代碼:
[cpp]
- #include <stdlib.h>
- #include <stdio.h>
-
- void main()
- {
- char array1[] = { "123456" };
- char *pointer1 = "123456";
- }
匯編代碼:
[html]
- (gdb) disassemble main
- Dump of assembler code for function main:
- 0x08048394 <+0>: push %ebp
- 0x08048395 <+1>: mov %esp,%ebp
- 0x08048397 <+3>: sub $0x10,%esp
- 0x0804839a <+6>: movl $0x34333231,-0xb(%ebp)
- 0x080483a1 <+13>: movw $0x3635,-0x7(%ebp)
- 0x080483a7 <+19>: movb $0x0,-0x5(%ebp)
- 0x080483ab <+23>: movl $0x8048484,-0x4(%ebp)
- 0x080483b2 <+30>: leave
- 0x080483b3 <+31>: ret
- End of assembler dump.
- (gdb) x/7xb 0x8048484
- 0x8048484 <__dso_handle+4>: 0x31 0x32 0x33 0x34 0x35 0x36 0x00
- (gdb)
從<+6><+13><+19>三行可以看出,程序為array1分配了7bytes的內存空間,用來存儲“123456”+‘\0’。
而<+23>行表示將地址0x8048484賦給了pointer1,我們可以查看內存0x8048484之後內容,7bytes正好為“123456”+‘\0’,這裡pointer1只是一個指針,並沒有為其分配內存單元。
那麼下面的這段代碼就不難理解了。
[cpp]
- #include <stdlib.h>
- #include <stdio.h>
-
- void main()
- {
- char array1[] = { "123456" };
- char array2[] = { "123456" };
- char *pointer1 = "123456";
- char *pointer2 = "123456";
- }
匯編代碼:
[html]
- (gdb) disassemble main
- Dump of assembler code for function main:
- 0x08048394 <+0>: push %ebp
- 0x08048395 <+1>: mov %esp,%ebp
- 0x08048397 <+3>: sub $0x20,%esp
- 0x0804839a <+6>: movl $0x34333231,-0xf(%ebp)
- 0x080483a1 <+13>: movw $0x3635,-0xb(%ebp)
- 0x080483a7 <+19>: movb $0x0,-0x9(%ebp)
- 0x080483ab <+23>: movl $0x34333231,-0x16(%ebp)
- 0x080483b2 <+30>: movw $0x3635,-0x12(%ebp)
- 0x080483b8 <+36>: movb $0x0,-0x10(%ebp)
- 0x080483bc <+40>: movl $0x8048494,-0x4(%ebp)
- 0x080483c3 <+47>: movl $0x8048494,-0x8(%ebp)
- 0x080483ca <+54>: leave
- 0x080483cb <+55>: ret
- End of assembler dump.
- (gdb) x/7xb 0x8048494
- 0x8048494 <__dso_handle+4>: 0x31 0x32 0x33 0x34 0x35 0x36 0x00
- (gdb)
接著這段代碼也就順其自然了!
[html]
- (gdb) disassemble main
- Dump of assembler code for function main:
- 0x08048394 <+0>: push %ebp
- 0x08048395 <+1>: mov %esp,%ebp
- 0x08048397 <+3>: sub $0x20,%esp
- 0x0804839a <+6>: movl $0x34333231,-0xf(%ebp)
- 0x080483a1 <+13>: movw $0x3635,-0xb(%ebp)
- 0x080483a7 <+19>: movb $0x0,-0x9(%ebp)
- 0x080483ab <+23>: movl $0x34333231,-0x16(%ebp)
- 0x080483b2 <+30>: movw $0x3635,-0x12(%ebp)
- 0x080483b8 <+36>: movb $0x0,-0x10(%ebp)
- 0x080483bc <+40>: movl $0x8048494,-0x4(%ebp)
- 0x080483c3 <+47>: movl $0x804849b,-0x8(%ebp)
- 0x080483ca <+54>: leave
- 0x080483cb <+55>: ret
- End of assembler dump.
- (gdb) x/7xb 0x8048494
- 0x8048494 <__dso_handle+4>: 0x31 0x32 0x33 0x34 0x35 0x36 0x00
- (gdb) x/9xb 0x804849b
- 0x804849b <__dso_handle+11>: 0x31 0x32 0x33 0x34 0x35 0x36 0x37 0x38
- 0x80484a3 <__dso_handle+19>: 0x00
- (gdb)