为调整堆栈大小分配内存时出现问题

Issue in allocating memory for resizing stack

本文关键字:问题 内存 分配 调整 堆栈      更新时间:2023-10-16

我试着找出代码中的错误,但仍然找不到。我有一个Stack类Album,我想调整它的大小,我认为我做得对。然而,由于某种原因,大多数时候程序都会崩溃,可能十分之一的程序运行良好,我不知道为什么。如果你能指出错误,那就太好了。这是代码:


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:
    ...
}

这里是函数,其中的某个地方是罪魁祸首。当我试图在相册中推送更多项目时,就会出现问题,而不是预定义的INIT_CAPITY=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]='';
}
Album::~Album()
{
    delete [] songs;
    delete [] name;
}

您的Song在应该使用std::string的地方也使用char*

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

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