1

Another question related to this https://stackoverflow.com/a/21213612/1423473

I'm trying to allocate memory for 3d array contiguously

    T* buff = new T [x * y * z];
    for(int i = 0; i < x * y * z; i++) {
        buff[i] = 2; // 2 for debug purposes
    }

    T*** a = new T **[x];
    for(int i=0; i<x; ++i)
    {
        a[i] = (T**)(buff + (i * y * z));
        for(int j=0; j<y; ++j)
        {
            a[i][j] = (T*)(buff + i*y*z + j*z);
            for(int k=0; k<z; ++k)
            {
                a[i][j][k] = 0;
            }
        }
    }

This code leads to SIGSEGV at the line a[i][j][k] = 0

At the execution time I have this result in gdb

(gdb) n
343                 a[i][j] = (T*)(buff + i*y*z + j*z);
(gdb) x/20d buff
0xbb7350:   2   2   2   2
0xbb7360:   2   2   2   2
0xbb7370:   2   2   2   2
0xbb7380:   2   2   2   2
0xbb7390:   2   2   2   2
(gdb) x/20d a
0x87ac80:   12284752    0   8955856 0
0x87ac90:   -134410640  32767   -288938360  32767
0x87aca0:   -134496320  32767   -288949632  32767
0x87acb0:   -288949584  32767   -288949536  32767
0x87acc0:   -134300384  32767   -134795808  32767
(gdb) n
345                 for(int k=0; k<z; ++k)
(gdb) x/20d buff
0xbb7350:   12284752    0   2   2
0xbb7360:   2   2   2   2
0xbb7370:   2   2   2   2
0xbb7380:   2   2   2   2
0xbb7390:   2   2   2   2
(gdb) print (int)buff
$6 = 12284752

It looks for me very mysterious. What kind of mistakes I have in this code? Or there are some alternative solutions?

Community
  • 1
  • 1
erthalion
  • 3,094
  • 2
  • 21
  • 28
  • 2
    Now you are a [three-star programmer](http://c2.com/cgi/wiki?ThreeStarProgrammer), congratulations. ;) – Shoe Jan 19 '14 at 11:09
  • I have an excuse because initially it's not my code =) – erthalion Jan 19 '14 at 11:12
  • Then fix it by writing a 3D array class that holds and manages a contiguous block, and gives access to elements via three indices :) – juanchopanza Jan 19 '14 at 11:18
  • If you want to do only small changes to your code (and not rewrite it, as suggested by @juanchopanza), try removing all the casts. Your code uses them to hide compilation errors; removing them will reveal the errors; then you can fix them. – anatolyg Jan 19 '14 at 11:20
  • You should really toss the code completely, and use something like [this](http://stackoverflow.com/a/6465254/179910) extended to take a third dimension. This can be done with little or no effect on other code (except speeding it up and eliminating crashes). – Jerry Coffin Jan 19 '14 at 18:24

1 Answers1

1
a[i] = (T**)(buff + (i * y * z));

You are storing some of the pointers inside the buffer itself. I doubt this is intentional. Try this:

a[i] = new T*[y];

This one is fine, because it's supposed to point inside the buffer:

a[i][j] = (T*)(buff + i*y*z + j*z);
user253751
  • 57,427
  • 7
  • 48
  • 90