简体   繁体   中英

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);

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.

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