-2

I am implementing multibit trie in C. I am getting segmentation fault error. When I run the program. I don't know what is going wrong?

The node of Multi bit trie is like that:

struct MtNode{
        /* nodes is an array 8 elements. Each element is a pointer to its child node.*/
        MtNode* nodes[8];  // 2^stride = 2^3 = 8
        int   nexthop;
    };

Each node is initialized as following:

typedef MtNode node;
node *init_mtnode(){
    node *ret = (node*) malloc(sizeof(node));   
    int size = (int)pow(2,STRIDE);
    for (int i=0; i<size ; ++i)
    {
           ret->nodes[i] = NULL;
    }    
    ret->nexthop = -1;
    return ret;
}

Is anything wrong in init_mtnode method?

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
explorer
  • 737
  • 1
  • 8
  • 23
  • `MtNode* nodes[8];` --> `struct MtNode* nodes[8];` – BLUEPIXY Oct 03 '15 at 01:37
  • Are you sure it's c? In [tag:c] the declarations you have would be wrong, they are valid in [tag:c++] though. Also, don't cast `pow` to int like that, and you don't need to cast `malloc()` either, again *unless it's [tag:c++]*. – Iharob Al Asimi Oct 03 '15 at 01:38
  • If i dont cast malloc, I get compilation error. @iharob. and actually i use c++ compiler cause i need some library of c++ such maps.. but the work is just a procedual programming...that's why i put c tag – explorer Oct 03 '15 at 01:41
  • @BLUEPIXY...i tried with struct MtNode* nodes[8];....same error..segfault – explorer Oct 03 '15 at 01:42
  • No, you should put the tag corresponding to the programming language you use, for example you should use `new` instead of `malloc()` and also, `maps` is not a library they are part of `stl` from standard c++. – Iharob Al Asimi Oct 03 '15 at 01:42
  • @iharob i think tag is not a matter of concern right now – explorer Oct 03 '15 at 01:44
  • It is, the help you get depends on that. And c solutions might be a bad choice in c++ and c++ solutions will not generally work in c. Also, there are some situations where a c solution will not work in c++. – Iharob Al Asimi Oct 03 '15 at 01:46

1 Answers1

1

There are multiple possible reasons:

  1. You don't check malloc() for NULL, unlike new which would throw an exception, malloc() will return NULL if an error happens.

  2. You calculate the value of size and then loop size times, but your array can only hold 8 pointers.

Try this

typedef MtNode node;
node *init_mtnode()
{
    node *ret;
    int size;
    ret = static_cast<node *>(malloc(sizeof(node)));
    if (ret == NULL) /* check for NULL */
        return NULL;
    size = 2 << STRIDE;
    if (size >= 8)
        size = 7; /* maximum possible value */
    for (int i = 0 ; i < size ; ++i)
        ret->nodes[i] = NULL;
    ret->nexthop = -1;

    return ret;
}
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97