【发布时间】:2020-10-03 09:49:29
【问题描述】:
我的项目是一个动态数组包装器,例如 std::vector。这就是它的工作原理:
添加新元素时,如果为0,则分配内存(malloc),如果不为0,则使用新大小(realloc)重新分配。大小是元素的数量*字体大小
当获取一个已经添加的元素时,我通过将其索引乘以类型的大小并将其添加到分配内存的地址来计算地址
注意:我自己编写和读取内存,没有 memcpy 或 memset 之类的功能。这是我的项目所必需的。我应该可以这样做,如果可以,请不要提及(除非我执行错误,在这种情况下,请提及)
当我尝试使用 get(int index) 函数读取添加的元素时,我会收到“变量周围的堆栈已损坏”或“读取访问冲突”错误,具体取决于我尝试执行此操作的方式。
我在网上阅读了一下,发现我可能已经用 malloc 以某种方式破坏了堆。还阅读了我可以通过名为“valgrind”的东西找出错误所在,但它似乎只适用于 linux,而且我使用的是 windows。
这是我的代码(它被重写,所有错误检查都被删除以使其更小)。我得到错误的地方被评论:
template<class T>
class darr
{
public:
darr(void) {}
~darr(void) {
erase(); dealloc();
}
bool alloc(int elemc) {
this->elemc = elemc;
this->size = (elemc * sizeof(T));
this->end = (this->start + this->size);
if (this->start)
{
this->start = (T*)(realloc(this->start, this->size));
if (this->start)
{
this->end = (this->start + this->size);
return true;
}
}
else
{
this->start = (T*)(malloc(this->size));
if (this->start)
{
this->end = (this->start + this->size);
return true;
}
}
return false;
}
bool erase(void)
{
for (int i = 0; i <= this->size; ++i)
{
*(unsigned long*)(this->start + i) = 0;
}
return true;
}
bool dealloc(void)
{
free(this->start);
return true;
}
bool add(T obj)
{
void* end_temp = 0;
if (this->end) { end_temp = this->end; }
if (true == this->alloc(++this->elemc))
{
end_temp = this->end;
for (int i = 0; i <= sizeof(obj); ++i)
{
*(unsigned long*)((unsigned long)(end_temp)+i) = *(unsigned long*)((unsigned long)(&obj) + i);
}
}
return true;
}
T get(int i)
{
unsigned long siz = sizeof(T);
void* i_addr = this->start + (i * siz);
//T tempobj = 0;
T* tempobj = (T*)(malloc(sizeof(T)));
// without malloc - stack around var corrupted (happnens at last index in for loop, no matter what index it is)
// with malloc - read access violation
for (int i = 0; i <= siz; ++i)
{
*(unsigned long*)((unsigned long)(&tempobj)+i) = *(unsigned long*)((unsigned long)(i_addr)+i);
}
return *tempobj;
}
private:
T * start;
void* end;
int elemc, size;
};
【问题讨论】:
-
评论不用于扩展讨论;这个对话是moved to chat。
标签: c++ memory-management heap-memory heap-corruption