指針和數組

比較一下
char *s="hi,db";    
s[0]='H';
和
char s[10]="hi,db"
s[0]='H'
這兩個代碼片斷的區別
使用指針時報錯:
void main()
{
        char *s="hi,db";
        s[0]='H';
}
反彙編結果:
080483b4 <main>:
 80483b4:       55                      push   %ebp
 80483b5:       89 e5                   mov    %esp,%ebp
 80483b7:       83 ec 10                sub    $0x10,%esp
//char *s="hi,db"
 80483ba:       c7 45 fc a0 84 04 08    movl   $0x80484a0,-0x4(%ebp)
//s[0]="H",能夠看到當咱們試圖將0x48(ascii碼就是'H')寫入一個地址爲80484a0的內存中時,就會出錯
//由於這個內存快是存放常量字符串"hi,db",而常量字符串是放在.rodata段中的,也就是隻讀內存,因此不能將'H'寫道
//只讀內存中
 80483c1:       8b 45 fc                mov    -0x4(%ebp),%eax
 80483c4:       c6 00 48                movb   $0x48,(%eax)
//函數返回
 80483c7:       c9                      leave
 80483c8:       c3                      ret
使用數組卻沒有報錯:
void main()
{
        char s[10]="hi,db";
        s[0]='H';
}
反彙編結果:
080483b4 <main>:
 80483b4:       55                      push   %ebp
 80483b5:       89 e5                   mov    %esp,%ebp
 80483b7:       83 ec 10                sub    $0x10,%esp
//char s[10]="hi,db"
 80483ba:       c7 45 f6 68 69 2c 64    movl   $0x642c6968,-0xa(%ebp)
 80483c1:       c7 45 fa 62 00 00 00    movl   $0x62,-0x6(%ebp)
 80483c8:       66 c7 45 fe 00 00       movw   $0x0,-0x2(%ebp)
//s[0]="H"   將'H'寫到棧中的內存沒什麼問題
 80483ce:       c6 45 f6 48             movb   $0x48,-0xa(%ebp)
 80483d2:       c9                      leave
 80483d3:       c3                      ret
相關文章
相關標籤/搜索