Search code examples
cbinary-treebinary-search-treepass-by-referencefree

Error on try to free memory from a Binary Tree


I try to free the memory recursive, and when I try to display to tree, to show a message that the tree has been freed. The code for the delete is

void stergereArbore(ArboreBin*rad) {
    if (rad) {
        stergereArbore(rad->st);
        stergereArbore(rad->dr);
        free(rad->avion.model);
        free(rad->avion.preturi);
        free(rad);
    }
}

and for display is

void afisareSRD(ArboreBin*a) {
    if (a) {
        afisareSRD(a->st);
        afisareAvion(a->avion);
        afisareSRD(a->dr);
    }
    else {
        printf("Empty");
    }
}

and the error message. I`m kind of new to data structures, and maybe I misspelled something. enter image description here


Solution

  • The function deals with a copy of the head pointer of the tree. So changing of the copy does not influence on the original head pointer of the tree.

    Either you should pass the head pointer by reference to the function or you should return the pointer to the head from the function that the caller could set it to NULL.

    Here are two approaches

    void stergereArbore( ArboreBin **rad ) 
    {
        if ( *rad ) 
        {
            stergereArbore( &( *rad )->st );
            stergereArbore( &( *rad )->dr );
            free( *rad );
            *rad = NULL;
        }
    }
    

    And the function can be called like

    ArboreBin *rad = NULL;
    
    //...
    
    stergereArbore( &rad ); 
    

    Or

    ArboreBin * stergereArbore( ArboreBin *rad ) 
    {
        if ( rad ) 
        {
            rad->st = stergereArbore( rad->st );
            rad->dr = stergereArbore( rad->dr );
            free( rad );
            return NULL;
        }
    }
    

    And the function can be called like

    ArboreBin *rad = NULL;
    
    //...
    
    rad = stergereArbore( rad );