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 p开发者_如何学Cutting 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.
This doesn't work
std::wstring GaugeWid;
std::copy(GaugeStr.begin(), GaugeStr.end(), GaugeWid.begin());
when GaugeWid
doesn't have a size. And it doesn't convert the characters either.
If you want a wide string, use a wstringstream
.
@Bo spotted a good line (after the question was edited...). I agree.
Here is a suggestion to fix it:
GaugeWid.clear();
std::copy(GaugeStr.begin(), GaugeStr.end(), std::back_inserter(GaugeWid));
@kongr45gpen:
I suspect a threading bug:
- you are doing updates of a variable names GaugeStr (sounds like meter monitoring)
- the code breaks on innocuous assignment to ....... a global.
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.
I just tried it:
#include <iostream>
#include <sstream>
using namespace std;
string GaugeStr;
float someFloat() {
return (float) 3.41;
}
void someFunction() {
float pie = someFloat();
stringstream ss (stringstream::in | stringstream::out);
ss << pie;
GaugeStr = ss.str();
}
int main() {
someFunction();
someFunction();
return 0;
}
This compiles with gcc-compiler version 4.4.0 (running on Windows, IDE: CodeBlocks).
精彩评论