From: Christopher S. <cs...@ma...> - 2013-12-11 19:08:47
|
On 12/10/13 14:59, Florian Oswald wrote: > virtual void SetUp() { > n = 3; > m = 2; > blitz::Array<double,2> M1(n,m); > blitz::Array<double,2> M2(n,m); > M.push_back( &M1); > M.push_back( &M2); > T = new TClass(M); > } > which looks as if M1 (i.e. the element behind M.at(0)) was never > properly allocated. Or it went out of scope after SetUp finished. As I > said, the identical example but using arma::mat instead of the blitz > arrays worked, so I'm a bit confused. I tried to allocate M1 and M2 on > the heap with "new" but that didnt' work. That's exactly what happened: M1 and M2 are allocated on the stack (although their data members are still heap-allocated), and they go out of scope at the end of SetUp(). The erroneous value in your test reflects random junk on the stack that formerly contained the array's extent. Allocating M1 and M2 via pointer/new should indeed work, as shown in this bare-bones sample code: class TheClass { public: blitz::Array<int,1> * theArrays[2]; void init() { blitz::Array<int,1> * M1, * M2; M1 = new blitz::Array<int,1>(1); (*M1)(0) = 1; M2 = new blitz::Array<int,1>(1); (*M2)(0) = 2; theArrays[0] = M1; theArrays[1] = M2; printf("Init: Extents %d; %d\n", M1->extent(0),M2->extent(0)); printf("Init: Values %d; %d\n", (*M1)(0),(*M2)(0)); // M1 and M2 are heap-allocated, so they don't // go out of scope and get destroyed. In this // simplistic test, they also leak. } void test() { printf("Test: Extents %d; %d\n", theArrays[0]->extent(0), theArrays[1]->extent(0)); printf("Test: Values %d; %d\n", (*theArrays[0])(0),(*theArrays[1])(0)); } }; int main() { TheClass MC; MC.init(); MC.test(); return 0; } $ g++ foo.cpp; ./a.out Init: Extents 1; 1 Init: Values 1; 2 Test: Extents 1; 1 Test: Values 1; 2 (Using stack allocation fails on extents in the manner you describe, and attempting to access the nonexistent data causes a segfault.) |