将指针指向空指针时出现段错误

时间:2018-02-09 11:32:40

标签: c pointers segmentation-fault valgrind ansi-c

我可能遗漏了一些关于指针和内存管理的重要内容。 我正在建立一个双重链表。我有struct Node

struct Node {
    void* data;
    nodep prev;
    nodep next;
};

nodep是指向此类节点的指针的typedef:

typedef struct Node * nodep;

现在我编写了一个insertAt()函数,它取一个nodep lst,它基本上是指向列表中第一个元素的指针,或NULL表示空列表,{{1}插入元素的位置和av int pos,它是Node的有效负载。这是我的代码摘录,我收到错误:

oid* data

这就是我在nodep insertAt(nodep lst, int pos, void *data){ nodep new = malloc(sizeof(struct Node)); [...] new -> data = data; assert(new != NULL); printf("memory allocated!\n"); /* insert at last position */ if(pos == -1) { [...] /* insert at first position */ } else if (pos == 0) { if(lst == NULL) { new -> next = lst; lst = new; } else { [...] } /* insert at pos */ } else { [...] } return new; } 函数中调用insertAt()的方式:

main()

当我用valgrind运行我的程序时,我得到了一个

  

不在地址0x10的映射区域内访问

这段代码:

int i;
nodep lst = NULL;

insertAt(lst, 0, "test");

我想要做的是将lst = new; 指向nodep lst,然后是nodep new,这是列表的第一个元素。我真的不明白,为什么我会遇到这个错误。

提前感谢您的帮助。

干杯尼克

1 个答案:

答案 0 :(得分:1)

如果你想修改lst,你必须使用双指针。

为简单起见,我将使用int

int i;
int* ptr = &i;

func(ptr);
func(int* p){

   p = ....; //this won't change ptr!
}

func(&ptr);
func(int** p){

   *p = ....; //this will change ptr!
}

如果是双指针且sizeof(int) = 4sizeof(int*) = 4

 ---------------       ---------------        ---------------
|0x4|0x5|0x6|0x7|     |0x0|0x1|0x2|0x3|      |   |   |   |   |
 ---------------       ---------------        ---------------
 0x8 0x9 0xA 0xB      0x4 0x5 0x6 0x7         0x0 0x1 0x2 0x3
 address of p         address of ptr           address of i

*p将为您提供i的地址。这是ptr点的地址。这就是为什么使用双指针更改“外部”指针。