New operator cannot allocate memory

In my C ++ program, I need to process a large amount of information. I store this great information in a structure. structure...

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 use the new operator to allocate memory for it

 struct xlsmain *interface = new xlsmain[60]; 

When the program starts, std::bad_alloc error displayed. Plese help!

+4
source share
3 answers

You are trying to allocate 60 xlsmain that 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 did not specify the definition of reportspecs . Thus, you are trying to allocate 3.8 billion things and run out of memory.

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

If these structures contain arrays, because structures can contain these objects, but usually they do not contain maxima, then get rid of arrays and replace them with std::vector (in C ++) or pointers (in C or C ++). Using any method, you will use just the space for the actual objects, as well as some overhead, instead of using the space for the maximum possible theoretical. std::vector allows you to add elements as needed, and the std::vector application takes care of allocating the necessary memory. With pointers, you have to allocate and free up space yourself.

+12
source

It is quite simple. You do not have enough memory. Either buy some more memory or recycle your code. I would suggest that you replace your arrays with null vectors. Thus, you only need to increase the vectors to the size you need, instead of a constant fixed size. This will use less memory and be more flexible. For instance,

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

More precise advice is not possible without knowing exactly what you are trying to do.

+1
source

@ H2CO3 is correct.

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

0
source

Source: https://habr.com/ru/post/1440274/


All Articles