简体   繁体   中英

new operator unable to allocate memory

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!

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.

It's simple enough. You haven't got enough memory. Either buy some more memory or redesign your code. I would suggest that your replace your arrays with zero length vectors. That way you only need to grow the vectors to the size you actually need, instead of having a fixed size always. That will use less memory and be more flexible as well. For instance

  struct pio_subparts
   {
    vector<corners> corner; 
    string pio_name;     
   };

More precise advice isn't possible without knowing exactly what you are trying to do.

@H2CO3 is right.

In pure C use something like this: http://www.elook.org/programming/c/malloc.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM