You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言:通过内存地址查看及操作链表节点结构体内容

已知链表节点内存地址,如何直接查看并操作节点内容?

已知链表中某个节点的内存地址时,完全可以直接通过该地址查看并操作节点的value值或next指针,核心是在调试器里将裸地址强制转换成对应的结构体指针类型,再进行访问或修改。

示例代码

//--------------------------------
// Setting up a list of nodes
//--------------------------------
struct node {
    int value;
    struct node *next;
};

int main(void) {
    struct node *first = NULL;
    struct node *new_node;

    // setting up first node
    new_node = malloc(sizeof(struct node));
    new_node->value = 1;
    new_node->next = first;    
    first = new_node;

    // setting up second node
    new_node = malloc(sizeof(struct node));
    new_node->value = 2;
    new_node->next = first;
    first = new_node;

    // setting up third node
    new_node = malloc(sizeof(struct node));
    new_node->value = 3;
    new_node->next = first;
    first = new_node;

    return 0;
}

调试场景说明

在GDB调试时,已在return 0处设置断点,通过*&first可以查看链表的层级结构:

first
  0x6888fffb20
    value: 1
    next: 0x25acadb18c0
      value: 2
      next: 0x25acadb1880
        value: 3
        next: 0x0 // NULL
          value: 
          next: 

直接操作指定地址节点的方法

针对地址为0x52acadb18c0的节点,可通过以下GDB命令实现查看和修改:

1. 查看节点内容

将裸地址强制转换为struct node *类型后解引用,即可查看完整节点信息:

p *(struct node *)0x52acadb18c0

执行后会输出该节点的value和next指针值。

2. 修改节点的value值

使用强制类型转换定位到节点的value成员,直接赋值修改:

set ((struct node *)0x52acadb18c0)->value = 20

执行后该节点的value会被修改为20。

3. 修改节点的next指针

同样通过强制类型转换定位到next成员,赋值为目标地址(比如NULL或其他节点地址):

// 将next指针设为NULL
set ((struct node *)0x52acadb18c0)->next = 0x0

// 或者将next指向另一个已知节点地址,比如0x25acadb1880
set ((struct node *)0x52acadb18c0)->next = 0x25acadb1880

原理说明

GDB支持直接使用C语言的类型转换语法,将裸内存地址转换成对应结构体指针后,就可以像操作普通结构体指针一样访问或修改其成员,无需依赖链表头节点的内存偏移。

内容的提问来源于stack exchange,提问作者user97662

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 10:54:19