2010年6月16日

GDB中如何存取不在current context的static variable

下午和 型男hasashi 討論一個malloc/free的問題,他寫了一個小程式來驗證malloc是否會自動free這件事,但是會 segmentation fault,我就想說開GDB來debug,同時練習GDB的用法。(自從上次在元智大學聽 變態 高手 Jserv 講解過GDB就一直在找機會練習 :D)

雖然說事後想一想這小程式其實意義不大,所以這程式邏輯是什麼也就不是重點了XD 但是碰到一個很有趣的GDB問題,所以想筆記一下。

這程式中,main會call一個function,裡面建立一個 static variable叫xxx,我想監看這個變數,不過如果程式離開這個function回到main了,我們在gdb裡要p(print)這個變數會出現:

No symbol "xxx" in current context.

所以我知道這個static variable其實存在,但是我看不到。雖然發現用把xxx加到display卻可以印出,我也不知道為什麼?(補充一下display的作用:每次breakpoint被觸發的時候,有被加到display裡的參數會自動被gdb print出來,就不用手動print。) 而且,只有display並不夠,因為有時會想存取這個變數來複製、assign給別的變數或做別的動作。

於是我先去 stackoverflow 找,但並沒有找到相關討論;接著我去google "gdb static variable No symbol  in current context",發現答案就在 gdb manual 裡;在 "Examining Data" 這一章的 "Program Variables" 這一節提到:

...If you wish, you can specify a static variable in a particular function or file, using the colon-colon (::) notation:
file::variable
function::variable
Here file or function is the name of the context for the static variable....

所以就可以很快樂的用 function::xxx 這種方式來存取不在current context的static variable了!

ps. 也許這就是沒先k過manual的報應啊…可是 gdb manual 有整整 32 章耶(不含一堆附錄)!?而且又不是只有gdb要看,想看的文件太多了,要怎麼取得平衡對我來說還是一個未解的問題…。

ps2. 在使用"gdb --tui"時曾經碰到好幾次上方視窗的source code會突然亂掉,發現別人也有碰過這個問題,但是暫時不知道解法,也許要找一個好的front-end來用。


3 則留言:

CrBoy 提到...

嗨,找資料碰巧看到您的文章。
gdb的tui模式也許可以試著用Ctrl+L來重新整理看看。:)

Will Wang 提到...

@CrBoy:
感謝您的資訊!
不知道這算是gdb的bug嗎?

匿名 提到...

How to make money from sports betting
This will make the sport more profitable 1xbet and งานออนไลน์ more profitable for many sports fans as well. Some bookmakers offer free bets and cash to  Rating: 5 · ‎1 vote 제왕 카지노