Search code examples
cglib

Inserting into GLib Tree from different functions


I'm not sure if I'm missing something and that might make this question very stupid. But I can't understand why the hell it's failing after trying pretty much every approach one could have.

So, super simple, I have this GLib Tree and I want to insert stuff into it in other functions. Why none of the options presented below work? I can understand the first failing more than the second to be completely honest.

int compare_ints(gconstpointer gpa, gconstpointer gpb){
     int a = *((int*) gpa);
     int b = *((int*) gpb);
     return (a-b);
 }

void test1(GTree* tree){
     int code = 1234;
     gpointer gcp = &code;
     g_tree_insert(tree, gcp, gcp);
     printf("%d\n", (g_tree_lookup(tree, gcp) == NULL)); // Outputs 0 (obviously)
 }

 void test2(GTree** tree){
     int code = 1234;
     gpointer gcp = &code;
     g_tree_insert(*tree, gcp, gcp);
     printf("%d\n", (g_tree_lookup(*tree, gcp) == NULL)); // Outputs 0 (obviously)
 }

 int main(int argc, char** argv){
     GTree* tree = g_tree_new(compare_ints);
     int code = 1234;
     gpointer gcp = &code;
     test1(tree);
     printf("%d\n", (g_tree_lookup(tree, gcp) == NULL)); // Outputs 1 (Why?)
     test2(&tree);
     printf("%d\n", (g_tree_lookup(tree, gcp) == NULL)); // Outputs 1 (Why?)

     return 0;
 }

Sorry about it if it's a stupid question, any help at all apreciated :)

Edit: Removed vim line notation


Solution

  • As @UnholySheep mentioned in the comments of the main thread, doing the following would work:

    void test1(GTree* tree, int* code){
        g_tree_insert(tree, code, code);
        printf("%d\n", (g_tree_lookup(tree, code) == NULL));
    }
    
    void test2(GTree** tree, int* code){
        g_tree_insert(*tree, code, code);
        printf("%d\n", (g_tree_lookup(*tree, code) == NULL));
    }
    
    int main(int argc, char** argv){
        Catalog* c = init_catalog(26, 1, compare_ints);
        int* code = malloc(sizeof(int));
        *code = 1234;
    
        GTree* tree = g_tree_new(compare_ints);
        test1(tree, code);
        printf("%d\n", (g_tree_lookup(tree, code) == NULL));
        test2(&tree, code);
        printf("%d\n", (g_tree_lookup(tree, code) == NULL));
    
        destroy_catalog(c);
        free(code);
        return 0;
    }
    

    The reason this works is because code only dissapears when you free it!

    On the initial case in the end of the function the int would stop existing and that would justify the behavior. If your interested in reading more about it check out the link that UnholySheep mentioned in the comments of the main thread!