我是 C++ 内存管理的新手,我遇到了这个奇怪的堆损坏错误(加上它之前的 Visual Studio 中的自动断点)。这是有问题的代码:
z_world::z_world(char* name)
{
unsigned int i, skip;
char tmp;
//Load data from file
std::string* data = loadString(name);
//Base case if there is no world data
tiles = NULL;
w = 0;
h = 0;
if(data->length() > 0) {
//Set up the 'tiles' array
for(i = 0; i < data->length(); i++) {
if(data->at(i) == '\n')
h++;
if(h == 0)
w++;
}
tiles = new int[data->length()-h];
//Load Data
skip = 0;
for(i = 0; i < data->length(); i++) {
if(data->at(i) == '\n') {
skip++;
printf("\n");
continue;
}
tmp = data->at(i);
tiles[i+skip] = atoi(&tmp);
printf("%i ",tiles[i+skip]);
}
}
delete data;
}
这是我在字符串中加载的位置:
std::string* loadString(char* name)
{
ifstream in(name);
std::string* input = new string();
while(in) {
std::string line;
getline(in,line);
input->append(line);
input->append("\n");
}
in.close();
return input;
}
我在“删除数据;”中得到了断点和错误,这让我觉得“数据”在此之前的某个地方被删除了,但我找不到它会在哪里。作为引用,此方法是创建一个包含游戏世界数据的对象,其形式为虚拟二维整数数组(用于图 block 的 ID)。
最佳答案
你的问题可能出在这里:
tiles[i+skip] = atoi(&tmp);
问题一:
应该是-skip
tiles[i - skip] =
问题2:
atoi()
命令使用不当(tmp 不包含字符串)。但我也不认为 atoi()
是合适的方法。我认为您正在寻找的是简单的任务。从 char 到 int 的转换是自动的:
tiles[i - skip] = tmp;
问题3:
您没有正确使用对象。在这种情况下,不需要生成动态对象并使用动态内存管理造成困惑。只创建自动对象并正常将它们传回会更简单:
std::string* loadString(char* name)
// ^ Don't do this.
std::string loadString(std::string const& name)
// ^^^^^^^ return a string by value.
// The compiler will handle memory management very well.
一般来说,你不应该四处传递指针。在您确实需要指针的少数情况下,它们应该保存在智能指针对象或容器(对于多个对象)中,以便正确控制它们的生命周期。
关于C++ - 删除 std::string*;堆损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11925353/