在创建缓冲区时将我的程序从使用数组切换为 vector 的最近更改中,出现了一个完全不相关的问题。此开关涉及创建 std::vector<std::vector<std::vector<GLfloat> > > terrainMap;
而不是 GLfloat[size+1][size+1][4] terrainMap
.为了初始化 3-D vector ,我使用
terrainMap.resize(size+1);
for (int i = 0; i < size+1; ++i) {
terrainMap[i].resize(size+1);
for (int j = 0; j < size+1; ++j)
terrainMap[i][j].resize(4);
}
这个“映射”是许多类的参数,通过void Terrain::Load(std::vector<std::vector<std::vector<GLfloat> > >& terrainMap,State ¤t){
修改内容作为程序的设置。这是一个奇怪的部分,当为纹理创建一个完全不相关的位图时,一个断点被击中并进一步导致堆损坏。这是图像加载的代码。
bmp = LoadBmp("dirt.jpg");
延伸到...
Bitmap Object::LoadBmp(const char* filename) {
Bitmap bmp = Bitmap::bitmapFromFile(ResourcePath(filename));
bmp.flipVertically();
return bmp;
}
此时 bmp 是具有正确格式 RGB 的 1600 x 1600 大小。然而,导致故障的是以下原因。
Bitmap& Bitmap::operator = (const Bitmap& other) {
_set(other._width, other._height, other._format, other._pixels);
return *this;
}
void Bitmap::_set(unsigned width,
unsigned height,
Format format,
const unsigned char* pixels)
{
if(width == 0) throw std::runtime_error("Zero width bitmap");
if(height == 0) throw std::runtime_error("Zero height bitmap");
if(format <= 0 || format > 4) throw std::runtime_error("Invalid bitmap format");
_width = width;
_height = height;
_format = format;
size_t newSize = _width * _height * _format;
if(_pixels){
_pixels = (unsigned char*)realloc(_pixels, newSize);
} else {
_pixels = (unsigned char*)malloc(newSize);
}
if(pixels)
memcpy(_pixels, pixels, newSize);
}
图像找到了通往 _pixels = (unsigned char*)realloc(_pixels, newSize);
的路_pixels 的内容指向不可读的内存。
令我感到奇怪的是,将 3-D 数组更改为 3-D vector 会导致此问题。两者之间没有相互作用。任何帮助深表感谢。
巨兽
最佳答案
您需要将像素数据保存在一个连续的缓冲区中,这意味着您需要一个 std::vector<GLfloat>
尺寸_width * _height * _format
而不是 vector 的 vector 。
使用 vector
而不是数组不会使您免于索引算法。它将使您免于像 Ed S. 在评论中指出的那样的内存泄漏。并且它将允许您完全摆脱赋值运算符,因为编译器提供的默认复制赋值(和移动赋值)运算符将工作得很好。
关于c++ - 切换到数组上的 vector 时位图加载中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16626715/