gdb 中 watch

1.  watch 變量的類型
    a. 整形變量: int i; watch i;
    b. 指針類型:  char *p; watch p, watch *p;
    它們是有區別的.
      watch p 是查看 *(&p), 是p 變量本身。
      watch (*p) 是 p 所指的內存的內容, 查看地址,一般是我們所需要的。

      我們就是要看莫地址上的數據是怎樣變化的,雖然這個地址具體位置只有編譯器知道。

    c. watch 一個數組或內存區間
    char buf[128], watch buf,  
    是對buf 的128個數據進行了監視. 此時不是採用硬件斷點,而是軟中斷實現的。
    軟中斷方式去檢查內存變量是比較耗費cpu資源的。
    精確的指明地址是硬件中斷。

2. 當你設置的觀察點是一個局部變量時。局部變量無效後,觀察點無效
 Watchpoint 2 deleted because the program has left the block in
  which its expression is valid.
               
3. 附上一個簡單程序方便你利用內存斷點觀察,調試.

$ cat test.cpp
#include <stdio.h>
#include <string.h>
void initBuf(char *buf);
void prtBuf(char *buf);
char mem[8];
char buf[128];
int main()
{
    initBuf(buf);
    prtBuf(buf);
    return 0;
}
 
void initBuf(char *pBuf)
{
    int i, j;
    mem[0]='0';
    mem[1]='1';
    mem[2]='2';
    mem[3]='3';
    mem[4]='4';
    mem[5]='5';
    mem[6]='6';
    mem[7]='7';
    //ascii table first 32 is not printable
    for(i=2;i<8;i++)
    {
        for(j=0;j<16;j++)
            pBuf[i*16+j]=i*16+j;
    }
}
 
void prtBuf(char *pBuf)
{
    int i, j;
    for(i=2;i<8;i++)
    {
        for(j=0;j<16;j++)
            printf("%c  ", pBuf[i*16+j]);
        printf("\n");
    }
}
 

玩弄內存調試於股掌之中。
(由於效率問題你需要適當控制內存斷點設置,當然,對這個小程序無所謂.)
----------------------------------------
看一下mem 數組, 內存數據是怎樣被寫入的。
----------------------------------------
gdb test
b main
watch mem
run
Breakpoint 1, main () at test.cpp:9
gdb) continue
  Continuing.
  Hardware watchpoint 2: mem
  Old value = "\000\000\000\000\000\000\000"
  New value = "0\000\000\000\000\000\000"
  initBuf (pBuf=0x6010a0 <buf> "") at test.cpp:18
(gdb) continue
  Continuing.
  Hardware watchpoint 2: mem
  Old value = "0\000\000\000\000\000\000"
  New value = "01\000\000\000\000\000"
  initBuf (pBuf=0x6010a0 <buf> "") at test.cpp:19
(gdb) continue
  Continuing.
  Hardware watchpoint 2: mem
  Old value = "01\000\000\000\000\000"
  New value = "012\000\000\000\000"
  initBuf (pBuf=0x6010a0 <buf> "") at test.cpp:20
(gdb)
......

(gdb) continue
  Continuing.
  Hardware watchpoint 2: mem
  Old value = "0123456"
  New value = "01234567"
  initBuf (pBuf=0x6010a0 <buf> "") at test.cpp:26
————————————————
版權聲明:本文爲CSDN博主「hjjdebug」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/hejinjing_tom_com/article/details/50570442

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章