I tried to create a 4D vector and display it like below in the console but the compiler says "Segmentation Fault (SIGSEGV)" in C++

  4d, c++, segmentation-fault, vector

This is my code (C++11):

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    
    vector<vector<vector<vector<int>>>> vect
    {
      {
        {
            {11, 12, 13},
            {14, 15, 16},
            {17, 18, 19}
        },
        {
            {21, 22, 23},
            {24, 25, 26},
            {27, 28, 29}
        },
        {
            {31, 32, 33},
            {34, 35, 36},
            {37, 38, 39}
        }
      },
      {
        {
            {41, 42, 43},
            {44, 45, 46},
            {47, 48, 49}
        },
        {
            {51, 52, 53},
            {54, 55, 56},
            {57, 58, 59}
        },
        {
            {61, 62, 63},
            {64, 65, 66},
            {67, 68, 69}
        }
      },
      {
        {
            {71, 72, 73},
            {74, 75, 76},
            {77, 78, 79}
        },
        {
            {81, 82, 83},
            {84, 85, 86},
            {87, 88, 89}
        },
        {
            {91, 92, 93},
            {94, 95, 96},
            {97, 98, 99}
        }
      }
    };

    for(int i = 0; i < vect.size(); i++)
    {
      for(int j = 0; j < vect[i].size(); j++)
      {
        for(int k = 0; k < vect[i][j].size(); k++)
        {
          for(int l = 0; l < 3; l++)
          {
            for (int m = 0; m < vect[i][j][k].size(); m++)
            {
              cout << vect[i][j+l][k][m] << " ";
            }
            cout << " ";      
          }
          cout << endl;
        }
        cout << endl;
      }
    }

    return 0;
}

The output I expected:

11 12 13  21 22 23  31 32 33  
14 15 16  24 25 26  34 35 36  
17 18 19  27 28 29  37 38 39  

41 42 43  51 52 53  61 62 63  
44 45 46  54 55 56  64 65 66  
47 48 49  57 58 59  67 68 69  

71 72 73  81 82 83  91 92 93  
74 75 76  84 85 86  94 95 96  
77 78 79  87 88 89  97 98 99  

And this is what happened:

Segmentation Fault (SIGSEGV)

11 12 13  21 22 23  31 32 33  
14 15 16  24 25 26  34 35 36  
17 18 19  27 28 29  37 38 39  

I don’t know how to fix this error.

Source: Windows Questions C++

LEAVE A COMMENT