- 論壇徽章:
- 0
|
原帖由 Fixend 于 2008-12-13 19:10 發(fā)表 ![]()
簡(jiǎn)單一點(diǎn)說(shuō), “abc”是const char *型的,數(shù)據(jù)放在只讀的內(nèi)存區(qū)。
而char[]在棧,可寫。
我為剛才的發(fā)帖感到臉紅~~,你是對(duì)的,
char str1[]="abcd";
char str2[]="efgh";
*str1=*str2;
|
的匯編代碼是: .file "2x.c"
.section .rodata
.LC0:
.string "abcd"
.LC1:
.string "efgh"
.text
.globl main
.type main, @function
main:
leal 4(%esp), %ecx
andl $-16, %esp
pushl -4(%ecx)
pushl %ebp
movl %esp, %ebp
pushl %ecx
subl $16, %esp
#put .LC0 in -9(%ebp) to -5(%ebp)
movl .LC0, %eax
movl %eax, -9(%ebp)
movzbl .LC0+4, %eax
movb %al, -5(%ebp)
#put .LC1 in -14(%ebp) to -10(%ebp)
movl .LC1, %eax
movl %eax, -14(%ebp)
movzbl .LC1+4, %eax
movb %al, -10(%ebp)
#*str1 = *str2
#not arrange address ,but arrange the first char;
movzbl -14(%ebp), %eax
movb %al, -9(%ebp)
# all done
addl $16, %esp
popl %ecx
popl %ebp
leal -4(%ecx), %esp
ret
.size main, .-main
.ident "GCC: (GNU) 4.2.3 (Debian 4.2.3-5)"
.section .note.GNU-stack,"",@progbits
|
char *str1="abcd";
char *str2="efgh";
*str1=*str2;
|
的匯編代碼如下:
.file "3x.c"
.section .rodata
.LC0:
.string "abcd"
.LC1:
.string "efgh"
.text
.globl main
.type main, @function
main:
leal 4(%esp), %ecx
andl $-16, %esp
pushl -4(%ecx)
pushl %ebp
movl %esp, %ebp
pushl %ecx
subl $16, %esp
movl $.LC0, -12(%ebp)
movl $.LC1, -8(%ebp)
movl -8(%ebp), %eax
movzbl (%eax), %edx
movl -12(%ebp), %eax
movb %dl, (%eax)
addl $16, %esp
popl %ecx
popl %ebp
leal -4(%ecx), %esp
ret
.size main, .-main
.ident "GCC: (GNU) 4.2.3 (Debian 4.2.3-5)"
.section .note.GNU-stack,"",@progbits
|
聲明為指針的時(shí)候,在棧上保存的是str的存儲(chǔ)地址,而str是聲明在.rodata區(qū)的,
所以最后
movl -12(%ebp), %eax
movb %dl, (%eax)
相當(dāng)于嘗試把str2的首字符寫入 .rodata區(qū),所以就SIGSEGV了,
而聲明為char []的時(shí)候,其實(shí)就是把字符在棧上操作,因此能正常執(zhí)行,
雖然這種操作沒(méi)啥意義~~ |
評(píng)分
-
查看全部評(píng)分
|