首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C 語言獲取變量與函數地址的方法及 GDB 調試技巧

     編輯:關於C語言

概述

在 C 語言編程與調試中,獲取變量、數組、字符串、函數的地址是常見需求。本文系統介紹各類實體的地址獲取方法,並演示如何使用 GDB 調試器查看函數地址。

1. 普通變量地址

使用取地址運算符 &:

int a = 1;
printf("address of a: %p\n", (void*)&a);

2. 數組地址

數組名本身即首元素地址,無需 加 &:

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](指向整個數組的指針),值雖相同但類型不同。

3. 字符串字面量/指針地址

字符串字面量存儲在只讀數據段,字符指針變量指向其首地址:

char *pStr = "string";
printf("address of string: %p\n", (void*)pStr); // 輸出字符串首地址
// 若為字符數組:
char str[] = "string";
printf("address of str: %p\n", (void*)str);     // 數組首地址

4. 函數地址

函數名即函數入口地址,可直接打印或賦值給函數指針:

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); // 直接用函數名

5. 完整示例程序

#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

6. 使用 GDB 查看函數地址

編譯時加 -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*) 避免警告。
  • GDB info address 是查看函數地址的權威方式,結合 disassemble 可進一步分析指令流。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved