Search code examples
c++stdvectorstdstring

How to read value of <std::vector<std::string>> *


I pass a std::vector<std::string>* to a function where I want to do something with each of the elements with type std::string. My code is the following but I get an error saying: terminate called after throwing an instance of std::bad alloc What did I do wrong?

void split_List(std::vector<std::string>* p_completeList) {
    
    std::vector<std::string>* v = new std::vector<std::string>();
    v= p_completeList;

    for(int i = 0; i < v->size(); ++i)
    {
            std::string value = (*v)[i];
            //...do some splitting, printing with value
    }
 }

Solution

  • When you call this function many many times eventually you will get a std::bad_alloc because you are allocations lots of memory that you immediately leak:

    // dynamically allocate a vector
    std::vector<std::string>* v = new std::vector<std::string>();
    // now v points to that new vector
    
    // throw away the last reference to the dynamically allocated vector
    v= p_completeList;
    // now v points to a different vector, the memory is leaked
    

    You should not do that. The function can be this:

    void split_List(std::vector<std::string>* p_completeList) {
        for(int i = 0; i < p_completeList->size(); ++i)
        {
                std::string value = (*p_completeList)[i];
                //...do some splitting, printing with value
        }
     }
    

    However, you should pass the vector by reference rather than via raw pointer, also to avoid such confusion as you are facing now. And there is (almost) never a good reason to allocate a std::vector via new.