实现基于指针的堆结构时的分段错误11

时间:2015-02-10 13:25:15

标签: c

我正在尝试实现堆数据结构,但是我无法运行以下代码。

我得到了

line 1: 47794 Segmentation fault: 11 

错误。

void heap_initialize(heap* p_heap){
  heap new_heap = {
    .size       = 0,
    .alloc_size = 1024,
    .root = NULL,
  };
  *p_heap = new_heap;
}

void heap_insert(heap* addr, void* p_thing, int priority) {
  heap my_heap = *addr;
  node* root   = my_heap.root;

  if (root == NULL) {
    my_heap.root = p_thing;
  }

  int i         = my_heap.size + 1;
  node new_node = {
    .thing    = p_thing,
    .priority = priority
  };

  node* new_node_addr = &new_node;

  node* child_addr = root + (i * 4);
  node child       = *new_node_addr;

  node* parent_addr = root + ((i / 2) * 4);
  node parent       = *parent_addr;

  while ( child.priority > parent.priority && root != &child ) {
    node* temp  = parent_addr;
    parent_addr = child_addr;
    child_addr  = temp;

    node child  = *child_addr;
    i           = i / 2;

    parent_addr = root + (i * 4);
    node parent = *parent_addr;
  }

主要

int main(int argc, char const *argv[])
{

  heap* addr = malloc(1024);
  heap_initialize(addr);

  char element[3] = "12";

  heap_insert(addr, element, 10);




  return 0;
}

从我能够阅读的内容来看,在尝试访问您无法访问的内存时会发生分段错误,但我无法弄清楚为什么 知道为什么会这样吗?

UPDATE 来自lldb调试器的结果

Process 47876 stopped
* thread #1: tid = 0x82070f, 0x0000000100000e0f heap`heap_insert + 207, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0x0)
    frame #0: 0x0000000100000e0f heap`heap_insert + 207
heap`heap_insert + 207:
-> 0x100000e0f:  movq   (%rcx), %rdi
   0x100000e12:  movq   %rdi, -0x88(%rbp)
   0x100000e19:  movq   0x8(%rcx), %rcx
   0x100000e1d:  movq   %rcx, -0x80(%rbp)

0 个答案:

没有答案