【发布时间】:2017-07-11 03:57:57
【问题描述】:
我正在尝试使用 c++ 完成解释器。原始版本运行良好。我尝试向它添加一个内存池和 gc。内存池类 MemPool 包含一个指向 MemList 的指针,而 MemList 包含指向 freelist 和 busylist 的指针。它们是指向 MemBlock 的指针,MemBlock 包含一个用于分配块的 void * 指针。
我覆盖了语法树节点的运算符 new 和 delete。运算符 new 仅用于 ASTree 基类,而 malloc 在其他情况下用作替代方案。 ASTree 是所有语法树节点的基类。
void *ASTree::operator new(size_t size){
cout<<"Using modified new operator!"<<endl;
void *buff=MemPool::getInstance()->alloc(size);
return buff;
}
void ASTree::operator delete(void *buff){
if(!MemPool::getInstance()->dealloc(buff))
throw MemoryError(curmodname,curline);
}
在声明节点中,我使用 unordered_map 来存储相关的子声明。
class DeclModule:public Declaration{
public:
DeclModule(const string &modname);
// ~DeclModule();
int getDeclType();
void intepret();
string modname;
unordered_map<string, DeclModule *> modulelist;
unordered_map<string, DeclClass *> classlist;
unordered_map<string, DeclMethod *> methodlist;
DeclEntry *entry;
};
我发现程序在不同的时间在不同的地方崩溃。我发现错误可能是由 unordered_map 引起的
DeclMethod *declmethod=methodParser();
declmodule->methodlist[declmethod->methodname]=declmethod;
有时 xcode 会在 __nd = __bucket_list_[__chash]; 中定位错误;
template <class _Key, class _Args>
_LIBCPP_INLINE_VISIBILITY
pair<typename __hash_table<_Tp, _Hash, _Equal, _Alloc>::iterator, bool>
__hash_table<_Tp, _Hash, _Equal, _Alloc>::__emplace_unique_key_args(_Key const& __k, _Args& __args)
#endif
{
size_t __hash = hash_function()(__k);
size_type __bc = bucket_count();
bool __inserted = false;
__next_pointer __nd;
size_t __chash;
if (__bc != 0)
{
__chash = __constrain_hash(__hash, __bc);
__nd = __bucket_list_[__chash];
if (__nd != nullptr)
{
for (__nd = __nd->__next_; __nd != nullptr &&
__constrain_hash(__nd->__hash(), __bc) == __chash;
__nd = __nd->__next_)
{
if (key_eq()(__nd->__upcast()->__value_, __k))
goto __done;
}
}
}
有时发现错误
__builtin_operator_delete(__ptr);
有时 xcode 告诉我不能使用 freed(指针还是内存?记不清了)。我确信在调用 unodered_map insert 时会发生错误。我想当我插入一个元素时,会调用 new 和 delete 。可能
需要你的帮助T-T,你能告诉我错在哪里以及如何修改它
【问题讨论】:
标签: c++ segmentation-fault overriding unordered-map