本文介绍了C++ 错误:双重释放或损坏(fasttop)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么以下程序在我运行程序时会收到错误double free or corruption (fasttop)".我知道我可以使用字符串而不是字符数组.但我想使用具有动态内存分配的字符数组.你能告诉我如何解决这个问题吗?

I'd like to know why the following program gets the error "double free or corruption (fasttop)" when I run the program. I know I can use string instead of character array. But I'd like to use character array with dynamic memory allocation. Could you please let me know how I can fix this problem?

#include <iostream>
#include <cstring>
#include <vector>
using namespace std;

class Cube
{
public:
    char *str;

    Cube(int len)
    {
        str = new char[len+1];
    }

    Cube(const Cube &c)
    {
        str = new char[strlen(c.str) + 1];
        strcpy(str, c.str);
    }
    ~Cube()
    {
        delete [] str;
    }
};

int main()
{
    vector <Cube> vec;

    for (int i = 0; i < 10; i++)
    {
        char in [] = "hello !!";
        Cube c(strlen(in)+1);
        strcpy(c.str, in);
        vec.push_back(c);
    }

    int i = 0;
    for ( vector<Cube>::iterator it = vec.begin(); it < vec.end(); )
    {
        cout << it->str << endl;
        i++;
        if (i % 2 == 0)
            it = vec.erase(it);
        else
            it++;
    }


    for ( vector<Cube>::iterator it = vec.begin(); it < vec.end(); it++)
    {
        cout << it->str << endl;
    }
    return 0;
}

推荐答案

您忘记为您的班级定义 operator=.这是三巨头的规则(copy ctor, dtor, assignment都必须定义).

You forgot to define operator= for your class. This is the rule of Big Three (copy ctor, dtor, assignment must all be defined).

这篇关于C++ 错误:双重释放或损坏(fasttop)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-02 03:10