为调整堆栈大小分配内存时出现问题
Issue in allocating memory for resizing stack
我试着找出代码中的错误,但仍然找不到。我有一个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
都包含无效指针。
相关文章:
- 如何针对特定情况调试和修复此双自由内存损坏问题
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 为什么瓦尔格林德在不释放恶意内存后没有报告任何问题?
- 包含矢量指针的结构的内存释放问题
- 在函数中分配内存时出现问题
- C++ 结构内部的unordered_map会导致内存泄漏问题吗?
- 使用 NTAllocateVirtualMemory 和 GetProcAddress 的内存分配问题不起作用
- 释放内存(主题模板)时出现问题
- C++ 中 std::vector 的内存问题
- C++ DLL 堆内存分配问题
- 在我的以下代码中获取 MLE(内存限制错误).尝试解决 ROUND C 2019(问题 A-摆动行走)启动问题
- 字符 * 未从重载运算符或内存管理问题正确返回
- delete[]有问题,如何部分删除内存
- 内存泄漏问题
- 指向动态内存中结构中的变量时出现问题
- c++中的内存管理问题
- C++堆栈内存管理问题
- 为什么我的C 代码在Linux上运行,而在Windows上不运行,是否有RAM内存的问题
- JNA 参数问题:内存访问无效
- boost的问题::内存映射~500MB,外部USB文件