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

标签 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;
}

最佳答案

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

它在析构函数中删除了 this 指针,但您尚未定义赋值运算符或复制构造函数。

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

关于c++ - 分配内存以调整堆栈大小的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23187131/

相关文章:

c++ - 找不到 BOOST_FILESYSTEM(缺少 : BOOST_FILESYSTEM_LIBRARIES)

c++ - 为什么这个内联汇编中的 ror op 不能正常工作?

c++ - 头文件中的类实现 == 糟糕的风格?

optimization - 两个纹理的非幂和内存消耗优化

c - 在c中使用动态分配输入字符串列表

c++ - 在 vector 末尾找到周期的最大频率的最快方法?

java - 如何在 Stock 类中进行用户定义输入

php - 无法重新声明类 - 检查类是否已存在

c++ - 如何使用提取运算符从 C++ 中的类的方法中获取多个值?

PHP 5.5,什么情况下PHP会导致committed memory很高