c++ - Bitmap Loading Breaks When Switching to Vectors over Arrays -
in recent change switch program using arrays vectors when creating buffer, totally unrelated problem surfaced. switch involves creation of std::vector<std::vector<std::vector<glfloat> > > terrainmap;
instead of glfloat[size+1][size+1][4] terrainmap
. initialize 3-d vector, use
terrainmap.resize(size+1); (int = 0; < size+1; ++i) { terrainmap[i].resize(size+1); (int j = 0; j < size+1; ++j) terrainmap[i][j].resize(4); }
this "map" parameter of many classes modify contents setup program through void terrain::load(std::vector<std::vector<std::vector<glfloat> > >& terrainmap,state ¤t){
strange part though, when creating totally unrelated bitmap for texturing, break point hit , going further results in heap corruption. here code image loading.
bmp = loadbmp("dirt.jpg");
which extends into...
bitmap object::loadbmp(const char* filename) { bitmap bmp = bitmap::bitmapfromfile(resourcepath(filename)); bmp.flipvertically(); return bmp; }
at point bmp proper 1600 1600 size correct format, rgb. is, however, following causes malfunction.
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); }
the image finds way _pixels = (unsigned char*)realloc(_pixels, newsize);
content of _pixels points unreadable memory. strikes me strange how changing 3-d array 3-d vector causes problem. no interaction between 2 occurring. appreciated. behemyth
you need keep pixel data in contiguous buffer, means need have one std::vector<glfloat>
of size _width * _height * _format
, not vectors of vectors.
using vector
instead of array won't save index arithmetic. save memory leaks 1 ed s. pointed out in comment. , allow rid of assignment operator entirely, since compiler-provided default copy assignment (and move assignment) operator work great.
Comments
Post a Comment