Ankita Saha
Ankita Saha

Reputation: 137

Segmentation fault in creating 2D array of large size in c++

I have allocated a 2D array of size 5000 x 4859 using new() in C++ from a file.

class input
{
public :
int **mytable;
int rows;
int columns;

input()
{
   rows=5008;
   columns=4859;


     std::ifstream file("test.txt");
     mytable=new int *[rows];

      for(int i=0;i<rows;i++)
      {
             mytable[i]=new int [columns];
      }

// read the input and inserted them into the array.
}
int ** gettable()
{
   return mytable;
}

Then in another function where am using mytable through a pointer.

void someFunction()
{
int ** table;
input file;
table= file.gettable();

// doing neccessary operations.

}

When I decrease the size of the table to 500 x 500, it works fine but for large size it gives an std:: bad alloc error . Where did I go wrong? Please help.

Upvotes: 2

Views: 409

Answers (2)

zobe kenobe
zobe kenobe

Reputation: 43

This should be of help,Creating large arrays in c++. Some relevant things you can think about when creating your arrays. {Though I can run and work with a 4000 by 4000 array of array (possibly because of the system configuration), it fails for 40000 by 40000.}

Upvotes: 2

orbitcowboy
orbitcowboy

Reputation: 1538

You are trying to allocate too much memory. Please take a look at bad_alloc:

std::bad_alloc is the type of the object thrown as exceptions by the allocation functions to report failure to allocate storage.

Obviously you exceed the allowed memory limit of your operating system.

Upvotes: 0

Related Questions