当我使用A *获取void *值并打印它时,命令终止

时间:2016-03-03 10:45:59

标签: c gdb

源代码粘贴在paste.ubuntu.com

为什么data = head->data;不起作用? 我的功能是

typedef struct Element 
{
   struct Element *next;
   void *data;
}
Element;

int pop(Element ** stack, void *data)
{
    if(!*stack) return 0;
    Element *head = *stack;
    data = head->data;
    *stack = head->next;
    free(head);
    head = NULL;
    //delete head;
    return 1;
}

gdb日志是这样的:

 - (gdb) b pop
 - Breakpoint 1 at 0x400675: file test.c, line 25.
 - (gdb) r
 - Starting program: /test     
 - Breakpoint 1, pop (stack=0x7fffffffda78, data=0x0) at test.c:25
 - 25       if(!*stack) return 0;
 - (gdb) l
 - 20       *stack = head;
 - 21       return 1;
 - 22   }
 - 23   int pop(Element ** stack, void *data)
 - 24   {
 - 25       if(!*stack) return 0;
 - 26       Element *head = *stack;
 - 27       data = head->data;
 - 28       *stack = head->next;
 - 29       free(head);
 - (gdb) n
 - 26       Element *head = *stack;
 - (gdb) 
 - 27       data = head->data;
 - (gdb) 
 - 28       *stack = head->next;
 - (gdb) p head->data
 - $1 = (void *) 0x602010
 - (gdb) p data
 - $2 = (void *) 0x0

我使用像这样的pop func

 A *a = NULL;
 pop(&stack,a);

结构:

typedef struct A {
    int val;
} A;

1 个答案:

答案 0 :(得分:0)

你几乎是对的。

你需要

pop(&stack, ((void**)&a));

而不是

pop(&stack,a);

您的pop函数应该是这样的:

int pop(Element ** stack, void **data) // modified
{
    if(!*stack) return 0;
    Element *head = *stack;
    *data = head->data;       // modified
    *stack = head->next;
    free(head);
    head = NULL;
    //delete head;
    return 1;
}

在原始代码中

A *a;
pop(&stack,a);

a不会被pop函数修改。如果您希望修改a,则必须将指针传递给a,并将pop函数传递给我修改后的代码