This is my function:
string GaugeStr;
void someFunction() {
float pie = someFloat();
stringstream ss (stringstream::in | stringstream::out);
ss << pie;
GaugeStr = ss.str();
}
When I run the function, it works properly. When I call it however for a second time (someFunction(); someFunction();, then my program crashes with a segmentation fault.
I tried putting stringstream ss (stringstream::in | stringstream::out); out of the function to make it a global variable, but the contents I want to send to GaugeStr get appended to ss. For example, if we assume that someFloat() always returns 1.2, then the second time I run the function, GaugeStr is set to 1.21.2.
So, I inserted ss.str("") in the function, but the program crashes again with a segfault.
What can I do to put the value of someFloat() is GaugeStr as a string without a segfault?
Exact Function
void CPU_BenchmarkFrame::OnButton1Click(wxCommandEvent& event) {
float pie = PiAlgo (Gauge2);
stringstream ss (stringstream::in | stringstream::out);
ss << pie;
wxMessageBox(_("Alert"), _("Sample Alert")); //To test where the segfault happens
string GaugeStr = ss.str();
wstring GaugeWid;
std::copy(GaugeStr.begin(), GaugeStr.end(), GaugeWid.begin());
StaticText2->SetLabel(GaugeWid);
}
Even more edits
The problem is one or more lines here:
wstring GaugeWid;
std::copy(GaugeStr.begin(), GaugeStr.end(), GaugeWid.begin());
StaticText2->SetLabel(GaugeWid);
when I commented them the script worked normally.
@Bo spotted a good line (after the question was edited…). I agree.
Here is a suggestion to fix it:
@kongr45gpen:
I suspect a threading bug:
Sounds like a threading bug. Do you use threads, if so, you must appropriately lock GaugeStr or make it a thread local.
Drop me a note if I need to expand on these, because at current I cannot be sure you are using threading.