srdja / Collections-C

A library of generic data structures for the C language.
http://srdja.github.io/Collections-C
GNU Lesser General Public License v3.0
2.8k stars 328 forks source link

Segfault when calling tree_min or tree_max with a sentinel node #171

Closed JaviMuller closed 10 months ago

JaviMuller commented 10 months ago

The functions tree_min and tree_max try to go through the treetable from the given node until finding a sentinel. However, when the function receives a sentinel, It will try to go to its children, which have been allocated with calloc to 0. As the children do not correspond to the sentinel, they will try to be dereferenced, causing a segfault. Here is a minimal program example that will trigger this segfault (the function get first key will use tree_min with the root node, which in this case is the sentinel).

#include "cc_treetable.h"
#include <stdio.h>

int cmp(const void *a, const void *b) {
    return *(int *)a - *(int *)b;
}

int main() {
    CC_TreeTable *table;
    int (*comp)(const void *, const void *) = &cmp;
    if (cc_treetable_new(comp, &table) != CC_OK)
        return -1;

    void *out;

    cc_treetable_get_first_key(table, &out);
    cc_treetable_destroy(table);
}