Reputation: 1389
I'm looking to build a 1D std::array
of structs, each of whose size is 16 bytes. The 1D array is a flattening of a class representing a 3D array (basically an std::array
wrapper that has some 3D specific operators and other fluff). My first attempt is an array of size 256 x 256 x 32, so roughly 35MB, which throws a SIGSEGV error.
A simplified example of everything looks like this:
Structs.cpp
struct Coord {
int x;
int y;
int z;
Coord() { }
Coord(int x_, int y_, int z_) { x = x_; y = y_; z = z_; }
}
int TR (int arg) {
// ... Some transformation
}
struct MyStruct {
Coord position;
int terrain;
MyStruct() { }
MyStruct(int x_, int y_, int z_, int terrain_) {
terrain = terrain_;
position = Coord(TR(x_), TR(y_), TR(z_));
}
}
ArrayWrapper.hpp
#include <array>
template <typename T, int HSIZE, int VSIZE> struct ArrayWrapper {
private:
std::array<T, HSIZE*HSIZE*VSIZE> narray;
public:
void set(T obj, int x, int y, int z) {
narray[x + z*HSIZE + y*HSIZE*HSIZE] = obj;
}
T& operator() (int x, int y, int z) {
return narray.at(x + z*HSIZE + y*HSIZE*HSIZE);
}
CoordinateMap.cpp
#include "ArrayWrapper.hpp"
#include "Structs.cpp"
const int HSIZE = 256;
const int VSIZE = 32;
class CMap {
private:
ArrayWrapper<MyStruct, HSIZE, VSIZE>* coords_ = new ArrayWrapper<MyStruct, HSIZE, VSIZE>;
ArrayWrapper<MyStruct, HSIZE, VSIZE> coords = *coords_;
public:
// ... Getter, setter, and a bunch of other methods,
~CMap() { delete coords; }
}
If I anywhere try to say CMap something;
I get a SIGSEGV. I know that the stack is relatively small, so I'm attempting to allocate this structure on the heap by using new
. Many people (on this site and others) say "Finding a large range of contiguous memory is difficult, even if it's on the heap," but don't give an indication of what a reasonable expectation of the size of contiguous memory is. I would think 32MB in a modern-day computer is doable.
What might be throwing a Seg. fault here?
Upvotes: 0
Views: 149
Reputation: 1389
ArrayWrapper<MyStruct, HSIZE, VSIZE> coords = *coords_;
Should be...
ArrayWrapper<MyStruct, HSIZE, VSIZE>& coords = *coords_;
... which makes sense. The 1st line is making a copy of coords_
' reference, which, in this case, defeats the purpose of using new
, since that copy is put on the stack.
Upvotes: 2