Search code examples
cgdbvalgrind

Make function pointers members of structures in c


I am completely noob when I work with C. Very weak with pointers.

I have written a struct for a binary search tree. But when I try to access it from code it throws an error:

Process terminating with default action of signal 11 (SIGSEGV). Bad permissions for mapped region at address 0x0`.

Here is my struct (in bst.h):

typedef struct tree Tree;

typedef struct tree{
    Node * root;
    Data * (*insert)(Tree * bst, Data value); //i get error in main when I make a call
    Data * (*search)(Tree * bst, Data value);
    void (*sort)(Tree *, Data *);
    int (*compare)(Tree *t, Tree * copy);
    Tree * (*clone)(Tree *t);
    void  (*delete)(Tree *bst);
    void  (*removeData)(Tree * bst, Data value);
}Tree;

Member functions (in bst.c):

Node * newNode(Data data, Node * parent) {
    printf("inside new node\n");
    Node * node = malloc(sizeof(Node));
    if(parent!=NULL) {
        if((parent->data.value)> data.value) {
            parent->left=node;
        }
        else {
            parent->right=node;
        }
    }
    node->parent=parent;
    node->left=NULL;
    node->right=NULL;
    node->data=data;
    printf("after inside newNode\n");
    return node;
}

Tree * newTree() {
    Tree *tree;
    tree = (Tree*)malloc(sizeof(Tree));
    tree->root=NULL;
    return tree;
}

// not getting inside in this function
Data * insert(Tree * tree, Data data) {
    if(tree->root==NULL) {
        tree->root = newNode(data,NULL);
    } else{
        return insertNode(tree->root,data);
    }
    return NULL;
}

Here is my main() that calls this function (in main.c):

Tree *bst = newTree();
assert(bst->root == NULL);

printf("1.");
for (i = 0; i < num_data; i++){
    bst->insert(bst, (Data){d[i]});
    printf("inside for loop");
}

I am not sure whether this is the right way to make function pointers as members of struct.


Solution

  • In newTree(), you are not assigning your functions to the function-pointers inside of the allocated tree struct.

    Data* insert(Tree* tree, Data data);
    // other function declarations as needed...
    
    Tree* newTree() {
        Tree *tree = (Tree*) malloc(sizeof(Tree));
        if (!tree) return NULL;
    
        tree->root = NULL;
    
        tree->insert = &insert; // <-- ADD THIS!
        // and do the same for your other function pointers...
        tree->search = ...;
        tree->sort = ...;
        tree->compare = ...;
        tree->clone = ...;
        tree->delete = ...;
        tree->removeData = ...;
    
        return tree;
    }