首页 > 解决方案 > 程序 _free_dbg(block, _UNKNOWN_BLOCK) 出错

问题描述

这是一本书的问题,我收到以下错误:_free_dbg(block, _UNKNOWN_BLOCK)

下面是一个类的实现代码:

template<class T>
Set<T>::Set(): items(NULL), num_items(0)
{
}

template<class T>
Set<T>::Set(const Set<T>& other)
{
    num_items = other.num_items;
    items = other.to_array();
}

template<class T>
Set<T>::~Set()
{
    if (items != NULL)
    {
        delete[] items;
    }
}

template<class T>
void Set<T>::operator= (const Set<T>& right_side)
{
    if (items != NULL)
    {
        delete[] items;
    }
    num_items = right_side.num_items;
    items = right_side.to_array();
}

template<class T>
void Set<T>::add(T item)
{
    if (!contains(item))
    {
        T *new_items = new T[num_items + 1];
        for (int i = 0; i < num_items; i++)
        {
            new_items[i] = items[i];
        }
        new_items[num_items] = item;
        if (num_items > 0)
        {
            delete[] items;
        }
        num_items++;
        items = new_items;
    }
}

template<class T>
void Set<T>::remove(T item)
{
    if (contains(item))
    {
        T *copy = NULL;
        if (num_items > 1)
        {
            copy = new T[num_items - 1];
            for (int i = 0, j = 0; i < num_items; i++)
            {
                if (items[i] != item)
                {
                    copy[j] = items[i];
                    j++;
                }
            }
        }
        delete[] items;
        items = copy;
        num_items--;
    }
}

template<class T>
int Set<T>::size() const
{
    return num_items;
}

template<class T>
bool Set<T>::contains(T item) const
{
    for (int i = 0; i < num_items; i++)
    {
        if (items[i] == item)
        {
            return true;
        }
    }
}

template<class T>
T *Set<T>::to_array() const
{
    T *copy = NULL;
    if (num_items > 0)
    {
        copy = new T[num_items];
        for (int i = 0; i < num_items; i++)
        {
            copy[i] = items[i];
        }
        return copy;
    }
}

我查了这个问题,我相信是导致这个问题的 delete[] 部分。有人可以告诉我错误是什么,我该如何纠正?

标签: c++

解决方案


好的,我已经解决了这个问题。

contains函数替换为Set.cpp

template<class T>
bool Set<T>::contains(T item) const
{
    for (int i = 0; i < num_items; i++)
    {
        if (items[i] == item)
        {
            return true;
        }
    }
    return false;
}

然后用你的print_set函数main.cpp替换这个:

template<class T> 
 void output_set(Set<T> myset) 
 { 
   T *ptr = myset.to_array(); 
   if (ptr != NULL) 
   { 
    for (int i = 0; i < myset.size(); i++) {
      cout << ptr[i] << endl;  } 
   }
   else { 
     cout << "The set is empty." << endl;
    } 
} 

解释

在函数中,找不到时contains忘记返回。这意味着在这种情况下该函数没有返回任何值,并且当您在将项目添加到检查有项目的语句时调用此函数时,此操作失败。falseitemSetif

现在对于该功能,即使您没有完成打印,您也print_set删除了循环中的每次,因此第一项打印正确,但其余项没有打印。ptr


推荐阅读