【发布时间】:2021-06-16 10:14:27
【问题描述】:
我正在尝试创建类似于堆栈的东西,但它是堆分配的。但是,当程序试图退出时,它说检测到堆损坏。我正在使用 Visual Studio 2019。
这是一个文件,其中包含一个名为 vstack 的类,它使用堆分配的字节数组:
#pragma once
#include<iostream>
#include<string>
#include<vector>
typedef unsigned char BYTE;
typedef BYTE* STACK;
struct VARIABLE {
std::string name;
int location = 0;
char type = 0;
};
class Vstack {
STACK vstack = nullptr;
int stack_top = 0, capacity = 0;
std::vector<VARIABLE> variables;
//resizes the byte array
void ReAlloc(size_t NewSize) {
STACK NewData = new BYTE[NewSize];
for (int i = 0; i != stack_top; i++)
NewData[i] = vstack[i];
delete[] vstack;
vstack = NewData;
capacity = NewSize;
}
public:
Vstack() {
ReAlloc(2);
}
//create a long long int stored on the vstack
void Create(std::string name, long long int value) {
if (stack_top + sizeof(long long int) >= capacity)
ReAlloc(capacity * 2);
VARIABLE var;
var.name = name;
var.location = stack_top;
variables.push_back(var);
*(long long int*)(vstack + stack_top) = value;
stack_top += sizeof(long long int);
}
//gets a pointer to a variable with the given name
void* Read(std::string name) {
for (int i = 0; i != variables.size(); i++)
if (variables[i].name == name)
return (vstack + variables[i].location);
return nullptr;
}
~Vstack() {
delete[] vstack;
}
};
这里是主文件:
#include<iostream>
#include"Vstack.h"
int main() {
Vstack stack;
stack.Create("x", 15);
std::cout << *(long long int*)stack.Read("x") << std::endl;
}
【问题讨论】:
-
不是造成它,而是在检测它。您在其他地方损坏了它,可能是由于运行不足或超出了数组边界。
-
调试器和/或静态内存分析器应该会发现内存损坏。
标签: c++ heap-memory heap-corruption