Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

new operator unable to allocate memory

Tags:

c++

In my C++ program I am required to handle large amount of information. I'm storing this large information in a structure. the structure is..

struct xlsmain
{
    struct sub_parts_of_interface sub_parts[200];
    string name;
    int no_of_subparts;
};

struct sub_parts_of_interface
{
    struct pio_subparts pio[10];
    string name_of_interface;
    string direction; 
    string partition;
    int no_of_ports;
};

struct pio_subparts
{
    struct corners corner[32]; 
    string pio_name;     
};

struct corners
{
    struct file_structure merging_files[50];
    string corner_name;
    int merginf_files_num;
};

struct file_structure
{
    string file_name;
    string file_type;
    struct reportspecs report[20];
};

I'm using new operator to allocate memory to it

struct xlsmain *interface = new xlsmain[60];

On running the program std::bad_alloc error is shown. Plese help!

like image 450
Cprog Avatar asked Dec 11 '22 21:12

Cprog


1 Answers

You are trying to allocate 60 xlsmain which contain 12,000 sub_parts_of_interface which contain 120,000 pio_subparts which contain 3,840,000 corners which contain 192,000,000 file_structure which contain 3,840,000,000 reportspecs, and you have not shown the definition of reportspecs. So you are trying to allocate 3.8 billion of something and are running out of memory.

That is because the system you are running on does not have enough memory to hold the objects you are trying to allocate.

If those structures contain arrays because the structures might hold those objects, but they usually do not contain the maximums, then get rid of the arrays and replace them std::vector (in C++) or pointers (in C or C++). With either method, you will use just space for the actual objects needed plus some accounting overhead, instead of using space for the maximum theoretically possible. std::vector allows you to add elements as needed, and the std::vector application will take care of allocating the needed memory. With pointers, you would have to allocate and free the space yourself.

like image 58
Eric Postpischil Avatar answered Dec 14 '22 10:12

Eric Postpischil