分配内存以调整堆栈大小的问题

时间:2014-04-20 20:17:53

标签: c++ oop memory-management constructor stack

我已经尝试过并试图在我的代码中找出错误,但我仍然无法找到它。我有一个Stack类专辑,我想调整大小,并认为我做得对。出于某种原因然而,大多数时候程序崩溃,也许十分之一的工作正常,我不知道为什么。如果你能指出错误那将是伟大的。所以这是代码:


const Song Song::null_song;//static from Song class

class Album
{
    Song* songs;
    char* name;
    int top;
    int capacity;
    bool full () const;
    void resize ();

public:
    ...
}

以下是函数,其中的某个部分是罪魁祸首。当我尝试在Album中推送更多项目然后预定义的INIT_CAPACITY = 4时会出现问题。我认为它应该有效,但它不会,所以问题必须是分配新的内存。


const int INIT_CAPACITY=4;

std::ostream& operator<<(std::ostream& os, Album& p)
{
    os<<"Name of Album:"<<p.name<<std::endl;
    for(int i=0;i<=p.top;i++)
        os<<p.songs[i]<<std::endl;
}

Album::Album(const char* p)
{
    int len1=strlen(p);
    name=new char [len1+1];
    strcpy(name,p);
    top=-1;
    songs = new Song[INIT_CAPACITY];
    capacity = INIT_CAPACITY;
}

Song Album::pop()
{
    if (empty())
        return Song::null_song;
    return songs[top--];
}

Song Album::last() const
{
    if (empty())
        return Song::null_song;
    return songs[top];
}

bool Album::push(Song x)
{
    if (full())
        resize();
    songs[++top] = x;
    return true;
}

void Album::resize()
{
    capacity *= 2;
    Song* newsongs = new Song[capacity];
    for(int i = 0; i < capacity / 2; i++)
        newsongs[i] = songs[i];
    delete[] songs;
    songs = newsongs;
}

bool Album::empty() const
{
    return top == -1;
}

bool Album::full() const
{
    return top == capacity-1;
}

Album::Album()
{
    top=-1;
    songs = new Song[INIT_CAPACITY];
    capacity = INIT_CAPACITY;

    name=new char [1];
    name[0]='\0';
}

Album::~Album()
{
    delete [] songs;
    delete [] name;
}

1 个答案:

答案 0 :(得分:1)

您的Song也使用char*std::string

它会在析构函数中删除此指针,但您还没有定义赋值运算符或复制构造函数。

一旦调整Song的大小,这会使所有Album包含无效指针。