简体   繁体   中英

c++ stringstream conversion error: segmentation fault

I am having some trouble with a simple function that tries to convert integers to a string. Here is the code:

string Problem::indexB(int i, int j, int k){    
    stringstream ss;

    if(i < 10)
        ss << "00";
    else if(i<100)
        ss << "0";
    ss << i;

    if(j < 10)
        ss << "00";
    else if(j<100)
        ss << "0";
    ss << j;

    if(k < 10)
        ss << "00";
    else if(k<100)
        ss << "0";
    ss << k;

    return ss.str();
}

The function works fine, but when a make multiple calls it gives me a segmentation fault in some point.

It works fine for me: http://ideone.com/lNOfFZ

Complete working program:

#include <string>
#include <sstream>
#include <iostream>

using std::string;
using std::stringstream;

class Problem {
public:
    static string indexB(int i, int j, int k);
};

string Problem::indexB(int i, int j, int k){

    stringstream ss;

    if(i < 10)
        ss << "00";
    else if(i<100)
        ss << "0";
    ss << i;

    if(j < 10)
        ss << "00";
    else if(j<100)
        ss << "0";
    ss << j;

    if(k < 10)
        ss << "00";
    else if(k<100)
        ss << "0";
    ss << k;

    return ss.str();
}

int main() {
    std::cout << Problem::indexB(1, 2, 3) << "\n";
    std::cout << Problem::indexB(400, 50, 6) << "\n";
    std::cout << Problem::indexB(987, 65, 432) << std::endl;
}

Segmentation faults often happen a while after the program has run into something with Undefined Behavior, so the stack trace when the error was detected is not necessarily in the same function as the buggy code.

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