在 C 語言編程與調試中,獲取變量、數組、字符串、函數的地址是常見需求。本文系統介紹各類實體的地址獲取方法,並演示如何使用 GDB 調試器查看函數地址。
使用取地址運算符 &:
int a = 1;
printf("address of a: %p\n", (void*)&a);
數組名本身即首元素地址,無需 加 &:
int set[3];
printf("address of set: %p\n", (void*)set); // 等價於 &set[0]
printf("address of set: %p\n", (void*)&set[0]); // 同樣結果
注意:&set 類型是 int (*)[3](指向整個數組的指針),值雖相同但類型不同。
字符串字面量存儲在只讀數據段,字符指針變量指向其首地址:
char *pStr = "string";
printf("address of string: %p\n", (void*)pStr); // 輸出字符串首地址
// 若為字符數組:
char str[] = "string";
printf("address of str: %p\n", (void*)str); // 數組首地址
函數名即函數入口地址,可直接打印或賦值給函數指針:
int hello() { printf("hello\n"); return 0; }
int show() { printf("show\n"); return 0; }
int (*pFunc)() = hello; // 函數指針
printf("address of Function: %p\n", (void*)pFunc);
printf("address of show: %p\n", (void*)show); // 直接用函數名
#include <stdio.h>
int hello() { printf("hello \n"); return 0; }
int show() { printf("show function is running \n"); return 0; }
int main() {
int a = 1;
int set[3];
char *pStr = "string";
int (*pFunc)() = hello;
printf("address of a :%p \n", (void*)&a);
printf("address of set :%p \n", (void*)set);
printf("address of string:%p \n", (void*)pStr);
printf("address of Function:%p \n", (void*)pFunc);
printf("address of show :%p \n", (void*)show);
return 0;
}
運行結果示例:
address of a :0x7ffd12345678
address of set :0x7ffd12345680
address of string:0x4006a0
address of Function:0x400566
address of show :0x40057a
編譯時加 -g 生成調試信息:
gcc -g show_address.c -o show_address
啟動 GDB 並設置斷點:
gdb show_address
(gdb) start
(gdb) info address hello
Symbol "hello" is a function at address 0x400566.
(gdb) info address show
Symbol "show" is a function at address 0x40057a.
(gdb) info address main
Symbol "main" is a function at address 0x40058e.
info address <function> 可直接顯示函數在代碼段的虛擬地址,極大地方便動態分析、斷點設置與逆向工程。
&var,數組/字符串/函數名直接用標識符即可獲取地址。%p 並轉型 (void*) 避免警告。info address 是查看函數地址的權威方式,結合 disassemble 可進一步分析指令流。