0

I am trying to implement a min heap in C but I am struggling with the sift down function.

What I have so far is :

    static void sift_down(t_heap *h, int cur)
    {
      int  min;

      if (!h->nodes[cur * 2] && !h->nodes[cur * 2 + 1])
        return ;
      else
      {
          if (!(h->nodes[cur * 2] && h->nodes[cur * 2 + 1]))
          {
              min = (h->nodes[cur * 2]) ? cur * 2 : cur * 2 + 1;
              if (h->nodes[cur]->value > h->nodes[min]->value)
              {
                  swap(&(h->nodes[cur]), &(h->nodes[min]));
                  sift_down(h, min);
              }
          }
          else
          {
              (min = (h->nodes[cur * 2]->value < h->nodes[cur * 2 + 1]->value) ? cur * 2 : cur * 2 + 1);
              if (h->nodes[cur]->value > h->nodes[min]->value)
              {
                  swap(&(h->nodes[cur]), &(h->nodes[min]));
                  sift_down(h, min);
              }
          }
      }
  }

I am sorry about the ternary conditions, I know most people dont like them, but this is for school and they force us to use ternaries.

This is currently segfaulting and I have no idea why. I tried valgrind but it didnt really help... If anyone has an idea that would be really great.

Mazhar
  • 575
  • 5
  • 20
Henry
  • 149
  • 2
  • 8
  • 2
    A segfault can often (not always) be most easily debugged with a debugger (not a memory tracer like valgrind). If you're using the GCC toolchain, compile your program with `-g` to include debugging symbols. Then use `gdb programname` to start the GNU debugger, and make it load your program. Use `run` to run your program till it crashes, and then use `backtrace` to find out where exactly it crashed. You can `print` values of local variables, and you can jump into a frame of the backtrace using the `frame` command. – Marcus Müller May 21 '16 at 18:29
  • 1
    Most probably you're trying to access elements beyond the size of `h->nodes[]`. If you don't have a debugger, you can add `printf()` all around to check indexes. – Matthieu May 21 '16 at 18:33
  • You are right. I replaced the lines if (!h->nodes[cur * 2] && !h->nodes[cur * 2 + 1]) return ; by if (cur * 2 > h->size) return; and everything seems to be working just fine :) – Henry May 21 '16 at 18:39

1 Answers1

0

I just replaced

    if (!h->nodes[cur * 2] && !h->nodes[cur * 2 + 1])
      return ;

by

    if (cur * 2 > h->size)
       return;

and everything is working just fine.

Henry
  • 149
  • 2
  • 8