Search code examples
c++vectortcp

Segmentation fault std::vector<std::string>


I write a function to return a vector and call it in other functions, in some function, it runs well, but in some, it throws the Segmentation fault. This is my functionA, it returns a vector

std::vector<std::string> functionA(std::vector<std::string>  l){
    ...

        char *list_inorder;
        int nnn = sprintf(list_inorder,"%-5d%-35s%-20s%-8s\n",(i),(s.at(1)).c_str(),(s.at(2)).c_str(), (s.at(0)).c_str());
        ...
    }
    return result;
}

This is how I call it in other function, I use the same method to call it but some can work some cannot.

std::vector<std::string> vectorA=functionA(vectorB);

Solution

  • You never point list_inorder to anything before you sprintf to it.

    That means undefined behavior. Intermittent crashes are expected from undefined behavior.

    Since you are using streams everywhere else, why not a stream for the output instead of sprintf? from memory ostringstream, but google will give a better answer than my memory...

    A simple fix would be to change char *list_inorder; to char list_inorder[50]; (assumes 50 chars is enough to fit your string) - this is not ideal and using streams would be better.