youngyangyang04 / Skiplist-CPP

A tiny KV storage based on skiplist written in C++ language| 使用C++开发,基于跳表实现的轻量级键值数据库🔥🔥 🚀

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

访问空跳表时,search会出错

EmiliaKKK opened this issue · comments

感谢您的项目!我在调试的过程中,如果直接对空跳表进行search,程序会崩溃,调试发现可能的问题在这里:

template<typename K, typename V> 
bool SkipList<K, V>::search_element(K key) {

    std::cout << "search_element-----------------" << std::endl;
    Node<K, V> *current = _header;

    // start from highest level of skip list
    for (int i = _skip_list_level; i >= 0; i--) {
        while (current->forward[i] && current->forward[i]->get_key() < key) {
            current = current->forward[i];
        }
    }

    //reached level 0 and advance pointer to right node, which we search
    current = current->forward[0];

    // if current node have key equal to searched key, we get it
    if (current and current->get_key() == key) {
        std::cout << "Found key: " << key << ", value: " << current->get_value() << std::endl;
        return true;
    }

    std::cout << "Not Found Key:" << key << std::endl;
    return false;
}

其中

current = current->forward[0];

使得getvalue会对空指针操作从而崩溃,修改一下这里应该就好啦


更新:非常抱歉,是我之前修改search代码时改动了返回值导致的错误,抱歉因为粗心打扰了。。。我的改动如下

template<typename K, typename V> 
V SkipList<K, V>::search_element(K key) {

    std::cout << "search_element-----------------" << std::endl;
    Node<K, V> *current = _header;

    // start from highest level of skip list
    for (int i = _skip_list_level; i >= 0; i--) {
        while (current->forward[i] && current->forward[i]->get_key() < key) {
            current = current->forward[i];
        }
    }

    //reached level 0 and advance pointer to right node, which we search
    current = current->forward[0];

    // if current node have key equal to searched key, we get it
    if (current and current->get_key() == key) {
        std::cout << "Found key: " << key << ", value: " << current->get_value() << std::endl;
        return current->get_value();
    }

    std::cout << "Not Found Key:" << key << std::endl;
    return current->get_value();
}

所以卡哥的原代码是没有问题的。。是我修改的疏忽。。。抱歉抱歉!