2020-04-12

How to solve the issue of not enough memory in C++ when vector's size is too large?

To test if two vectors are the same or not
See code below
#include <iostream>
#include <vector>
#include <string>
int main(void) {
    std::vector<std::string> vstr1(131, "asdf");
    std::vector<std::string> vstr2(33131, "asdf");

    std::cout << (vstr1 == vstr2) << std::endl;;
    std::cout << "******************************" << std::endl;

    return 0;
}
It works fine.
Now I change the size of vstr2 to be extremely large, like 33333333333131
#include <iostream>
#include <vector>
#include <string>
int main(void) {
    std::vector<std::string> vstr1(131, "asdf");
    std::vector<std::string> vstr2(33333333333131, "asdf");

    std::cout << (vstr1 == vstr2) << std::endl;;
    std::cout << "******************************" << std::endl;

    return 0;
}
Not working, and error message is
terminate called after throwing an instance of 'std::bad_alloc' 
what()  std::bad_alloc
Aborted    (core dumped)     a.out
I have gathered the error occurs due to memory allocation failure.
What can I do to deal with vector of really large size ?

1 comment:

Unknown said...

That is almost 1 PB in RAM. I would be surprised if it didn't error out.

How to Add a Directory to PATH in Linux

 https://linuxize.com/post/how-to-add-directory-to-path-in-linux/ When you type a command on the command line, you’re basically telling the ...